【问题标题】:Giving more than one maproutes in Webapicontroller在 Web Api Controller 中提供多个地图路由
【发布时间】:2012-09-02 03:46:38
【问题描述】:

我的 Web API 控制器中有两种方法,如下所示:

public samplecontroller: webapicontroller
{

     [HttpPost]    
     public void PostMethod()

     [HttpGet]
     public void GetValues(int a,int b)
}

我在 global.asax 中有以下内容:

 routes.MapHttpRoute

 ("Default API Route", "api/{controller}/{id1}/{id2}/{id3}/{id4}/{id5}", 

  new { id1 = UrlParameter.Optional, id2 = UrlParameter.Optional, id3 = UrlParameter.Optional, id4 = UrlParameter.Optional, id5 = UrlParameter.Optional });

如果我想调用第二种方法,即GetValues(int a,int b),我可以在Global.asax中再写一个HttpRoute如下吗?

routes.MapHttpRoute(
     name: "ActionApi",
     routeTemplate: "api/{Sample}/{GetValues}/{a}/{b}",
     defaults: new { a = UrlParameter.Optional, b=UrlParameter.Optional }
);

那么我可以在 global.asax 中创建多个 maproute 吗?

而且,为了提供可选参数,我应该只给像 a 和 b 这样的参数吗?

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 asp.net-mvc-4


    【解决方案1】:

    你可以在 global.asax 中有多个路由;每个传入的请求都将转到匹配的第一个路由。这意味着更具体的应该先行。如果满足以下条件,则 URL 与路由匹配:

    1. 定义了controlleraction 路由值。
    2. 定义了所有必需的路由值(路由中大括号中的值,以及操作中的不可为空的参数)。

    也就是说,您提出的路线 api/{Sample}/{GetValues}/{a}/{b} 没有意义。它创建了两个新的(无意义的)路由值SampleGetValues,并且不提供定义controlleraction。我想你的意思是这样写的:

    routeTemplate: "api/Sample/GetValues/{a}/{b}",
    defaults: new { controller: "Sample", action: "GetValues", a = UrlParameter.Optional ,b=UrlParameter.Optional }
    

    这会将 URI /api/Sample/GetValues/1/2 与您的操作相匹配。

    routeTemplate: "api/Sample/GetValues/{a}/{b}",
    defaults: new { controller: "Sample", action: "GetValues", a = UrlParameter.Optional ,b=UrlParameter.Optional }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      相关资源
      最近更新 更多