我有一个简单的 WebApi2 Controller ,它返回 XML,但我无法使用我定义的路由正确添加另一个方法:

namespace CBMI.WebAPIservice.Controllers
{
public class MarkersController : ApiController
{
    public HttpResponseMessage Get(int? id)
    {
        int i = id.HasValue ? id.Value : 0;
        XmlDocument docContent = GetXmlDataFromDB(i);
        return new HttpResponseMessage
        {
            Content = new StringContent(docContent.InnerXml.ToString(), Encoding.UTF8, "application/xml")
        };
    }
    public HttpResponseMessage GetGrantsIS()
    {
        XmlDocument docContent = GetXmlDataFromDB();
        return new HttpResponseMessage
        {
            Content = new StringContent(docContent.InnerXml.ToString(), Encoding.UTF8, "application/xml")
        };

    }
    public XmlDocument GetXmlDataFromDB()
    {
        string connStr = System.Convert.ToString(
                System.Web.Compilation.ConnectionStringsExpressionBuilder.GetConnectionString("MDWConnectionString"),
                System.Globalization.CultureInfo.CurrentCulture);
        SqlConnection conn = new SqlConnection(connStr);
        SqlCommand sqlCmd = new SqlCommand("dbo.FLAS_List_GrantLocationsByAmount_V1", conn);
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
        conn.Open();
        XmlDocument xmlDoc = new XmlDocument();
        XmlReader xmlReader = sqlCmd.ExecuteXmlReader();
        if (xmlReader.Read())
            xmlDoc.Load(xmlReader);
        conn.Close();
        return xmlDoc;
    }
    public XmlDocument GetXmlDataFromDB(int worldAreaID )
    {
        string scrambleAward = "";
        string connStr = System.Convert.ToString(
                System.Web.Compilation.ConnectionStringsExpressionBuilder.GetConnectionString("MDWConnectionString"),
                System.Globalization.CultureInfo.CurrentCulture);
        SqlConnection conn = new SqlConnection(connStr);
        SqlCommand sqlCmd = new SqlCommand("dbo.FLAS_List_Awards_V1", conn);
        sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
        sqlCmd.Parameters.AddWithValue("@AreaID", worldAreaID);
        sqlCmd.Parameters.AddWithValue("@Scramble", scrambleAward);
        conn.Open();
        XmlDocument xmlDoc = new XmlDocument();
        XmlReader xmlReader = sqlCmd.ExecuteXmlReader();
        if (xmlReader.Read())
            xmlDoc.Load(xmlReader);
        conn.Close();
        return xmlDoc;
    }

}

}

WebApiConfig.cs
namespace CBMI.WebAPIservice.App_Start
{
//  This code file defines the delegate where you should put your Web API configuration code.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute
            (
                name: "WebApi2",
                routeTemplate: "api/{controller}/{id}"
            );
        config.Routes.MapHttpRoute
            (
                name: "ApiGrantsIS",
                routeTemplate: "api/{controller}/{action}"
            );
    }
}

}

我无法理解如何更改路由以识别操作,以便调用 GetGrantsIS 方法。而是使用以下 URL 浏览
CBMI.WebAPIservice/api/markers/GetGrantsIS

路由到识别 id 没有值的 Get 方法。然后它的默认值为 0 并且它可以工作,但我需要让这个 URL 调用 GetGrantsIS 方法。

编辑:尝试添加属性路由会出现新错误

我装饰如下:
    [Route("api/{controller}/GetGrantsIS")]
    public HttpResponseMessage GetGrantsIS()

现在我明白了:

Server Error in '/CBMI.WebAPIservice' Application.

A direct route cannot use the parameter 'controller'. Specify a literal path in place of this parameter to create a route to a controller.

最佳答案

Web Api 2 支持 REST 架构,这意味着它期望您的操作是 GET、POST、PUT、DELETE。

但是,您可以使用 attribute routing 获得所需的结果。

如果您想使用属性路由,您的 WebApiConfig 文件中已经有该设置。因此,您只需要修改代码即可使用 Route 属性,如下所示:

[Route("api/markers/getgrantsis")]
public HttpResponseMessage GetGrantsIS()
{
  XmlDocument docContent = GetXmlDataFromDB();
  return new HttpResponseMessage
  {
    Content = new StringContent(docContent.InnerXml.ToString(), Encoding.UTF8, "application/xml")
   };

}

关于c# - 我的 web api 2 Controller 需要路由,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41351436/

10-17 00:15