在Web Api Controller中提供多个地图路线

时间:2012-09-02 03:46:38

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

我的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这样的参数吗?

1 个答案:

答案 0 :(得分:0)

您可以在global.asax中拥有多条路线;每个传入的请求将转到匹配的第一个路由。这意味着更具体的应首先出现。如果符合以下情况,则URL匹配路由:

  1. 定义了controlleraction路由值。
  2. 定义了所有必需的路由值(路由中的大括号中的两个以及Action中的非可空参数)。
  3. 也就是说,您建议的路线 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 }