我的Web API 2控制器需要路由 [英] need route for my web api 2 controller

查看:250
本文介绍了我的Web API 2控制器需要路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的WebApi2控制器,该控制器返回XML,但是我无法使用我定义的路由正确添加其他方法:

I have a simple WebApi2 controller that returns XML but I cannot add another method properly with the routing I have defined:

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}"
            );
    } 
}

}

我不明白如何更改路由以识别 action ,从而调用 GetGrantsIS 方法。而是使用以下URL浏览

I cannot understand how to change the routing to recognize the action such that the GetGrantsIS method is invoked. Instead, browsing with the following URL

CBMI.WebAPIservice/api/markers/GetGrantsIS

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

routes to the Get method which recognizes that id has no value. It then defaults to a value of 0 and it works but I need to have this URL invoke the GetGrantsIS method.

编辑:尝试添加属性路由会产生新错误

我装饰为如下:

    [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。

Web Api 2 favors REST architecture, meaning it expects your actions to be GET, POST, PUT, DELETE.

不过,您可以使用属性路由

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

If you wanted to use attribute routing you already have that setup in your WebApiConfig file. So you would just need to modify your code to use the Route attribute like so:

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

}

这篇关于我的Web API 2控制器需要路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆