简体   繁体   English

WebAPI中重载的Get方法的路由问题

[英]Routing issue with overloaded Get method in WebAPI

I have 2 Get methods in Product controller as below: 我在Product controller中有2个Get方法,如下所示:

public IHttpActionResult Get(string keywordSearch)

[Route("api/Product/{id:long}")]
public IHttpActionResult Get(long id)

The following url works: 以下网址有效:

http://localhost:61577/api/Product?keywordSearch=test
http://localhost:61577/api/Product/1

This one fails, with message: 此操作失败,并显示以下消息:

http://localhost:61577/api/Product/test

{    
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:61577/api/Product/test'.",
"MessageDetail": "No action was found on the controller 'Product' that matches the request."
}

The WebApiConfig.cs has following configurations: WebApiConfig.cs具有以下配置:

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

Please advice, what changes should I make in API function or Config to make that work. 请提出建议,我应该对API函数或Config进行哪些更改才能使其正常工作。

You would need to specify the routes in your routes configuration for both the action methods something like: 您需要在路由配置中为两种操作方法指定路由,例如:

// for number type parameter only
config.Routes.MapHttpRoute(
    name: "IdSearch",
    routeTemplate: "api/{controller}/{id}",
    defaults: null,
    constraints: new { id = @"^\d+$" } // Only integers 
);

and then register another one for string parameter : 然后为字符串参数注册另一个:

// for string parameter overload action route
config.Routes.MapHttpRoute(
    name: "KeyWordSearch",
    routeTemplate: "api/{controller}/{keywordSearch}",
    defaults: null
);

and in your action declaration apply propery attribute values on string parameter overload one, so that both will look like: 并在您的动作声明中对字符串参数重载之一应用属性属性值,这样两者都将类似于:

[Route("api/Product/{keywordSearch}")]
public IHttpActionResult Get(string keywordSearch)

[Route("api/Product/{id:long}")]
public IHttpActionResult Get(long id)

Another way is that you can use the RoutePrefix on your Controller class and then the Route attribute on your action methods, so that you don't have to duplicate the Prefix of Route on each action method: 另一种方法是,可以在Controller类上使用RoutePrefix ,然后在操作方法上使用Route属性,这样就不必在每个操作方法上重复Route的前缀:

[RoutePrefix("api/product")] 
public class ProductController : ApiController
{
    [Route("{keywordSearch}")] 
    public IHttpActionResult Get(string keywordSearch)

    [Route("{id:long}")]
    public IHttpActionResult Get(long id)
}

This should keep you going. 这应该让你继续前进。

Hope it helps! 希望能帮助到你!

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

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