我在Product controller中有2个Get方法,如下所示:
public IHttpActionResult Get(string keywordSearch)
[Route("api/Product/{id:long}")]
public IHttpActionResult Get(long id)
以下网址有效:
http://localhost:61577/api/Product?keywordSearch=test
http://localhost:61577/api/Product/1
这个失败了,消息:
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."
}
WebApiConfig.cs具有以下配置:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
请建议,我应该在API函数或Config中做出哪些更改才能使其工作。
答案 0 :(得分:1)
您需要在路线配置中为两种操作方法指定路线,例如:
// for number type parameter only
config.Routes.MapHttpRoute(
name: "IdSearch",
routeTemplate: "api/{controller}/{id}",
defaults: null,
constraints: new { id = @"^\d+$" } // Only integers
);
然后为字符串参数注册另一个:
// for string parameter overload action route
config.Routes.MapHttpRoute(
name: "KeyWordSearch",
routeTemplate: "api/{controller}/{keywordSearch}",
defaults: null
);
并在您的操作声明中对字符串参数重载1应用propery属性值,以便两者看起来像:
[Route("api/Product/{keywordSearch}")]
public IHttpActionResult Get(string keywordSearch)
[Route("api/Product/{id:long}")]
public IHttpActionResult Get(long id)
另一种方法是,您可以在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)
}
这应该让你继续前进。
希望它有所帮助!