简体   繁体   English

Web API 2中的多重路由

[英]Multiple Routing in Web API 2

I'm using Web API 2, I want to route using parameters such as (name & id). 我正在使用Web API 2,我想使用(name&id)等参数进行路由。

When I try this : 当我尝试这个:

config.Routes.MapHttpRoute(
            name: "IDApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "NameApi",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: new { name = RouteParameter.Optional }
        );

I got the route 'api/customer/getByID/5' worked fine. 我得到的路线“ api / customer / getByID / 5”工作正常。

But the route 'api/customer/searchByName/fawzy' didn't work. 但是路由“ api / customer / searchByName / fawzy”无效。

And if I set the NameAPI route before the IDAPI route the result is the opposite. 如果我在IDAPI路由之前设置NameAPI路由,则结果相反。

Any ideas ? 有任何想法吗 ?

您可以将[Route("api/customer/searchByName/{name}")]空间System.Web.Http.Routing [Route("api/customer/searchByName/{name}")]属性用于searchByName操作。

I solved this problem by a combination of Pattern & Route Attribute 我通过组合模式和路线属性解决了这个问题

In the WebAPIConfig file : WebAPIConfig文件中:

config.Routes.MapHttpRoute(
            name: "IDApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: null,
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "api/{controller}/{action}",
           defaults: null
       );

In the Controller : 控制器中

[HttpGet]
[Route("api/customer/search/{name}")]
public IHttpActionResult Search(string name)
{

}

[HttpGet]
public IHttpActionResult Get(int id)
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM