我正在尝试使用包含三种方法的[RoutePrefix("front")]
向控制器添加自定义路由:
[HttpGet]
[ResponseType(typeof(SparePartsFrontDTO))]
public async Task<IHttpActionResult> Get()
{
...
}
[HttpGet]
[ResponseType(typeof(IEnumerable<SparePartSearchDTO>))]
public async Task<IHttpActionResult> Get(string filter)
{
...
}
[HttpGet]
[Route("categories")]
[ResponseType(typeof(IEnumerable<DeviceCategoryDTO>))]
public async Task<IHttpActionResult> GetCategories()
{
...
}
但是当我通过路由api/front/categories
调用方法而不是自定义路由时,调用了默认的get方法。
这是WebApi配置:
config.MapHttpAttributeRoutes();
config.MessageHandlers.Add(new PreflightRequestsHandler());
config.SuppressDefaultHostAuthentication();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
答案 0 :(得分:1)
路由前缀需要包含所需的模板以及其他需要Route
属性的操作。
[RoutePrefix("api/front")]
public class MyController : ApiController {
[HttpGet]
[Route("")] // matches GET api/front
[ResponseType(typeof(SparePartsFrontDTO))]
public async Task<IHttpActionResult> Get() {
//...
}
[HttpGet]
[Route("filter/{filter}")] // matches GET api/front/filter/anything-here
[ResponseType(typeof(IEnumerable<SparePartSearchDTO>))]
public async Task<IHttpActionResult> Get(string filter) {
//...
}
[HttpGet]
[Route("categories")] //matches GET api/front/categories
[ResponseType(typeof(IEnumerable<DeviceCategoryDTO>))]
public async Task<IHttpActionResult> GetCategories() {
//...
}
}