我正在尝试将/action-figure/
看起来像ActionFigureController
的网址映射到config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
。即,让我的网址为控制器分隔连字符。
类似于this answer exactly,但是对于WebApi而不是MVC路由。
如何在WebApi中配置我的网址?
几乎所有谷歌搜索都指示我使用MVC路由配置,我无法找到它的等价物:
MvcRouteHandler
因为from rpg import *
print Setup.hello
不适用于此,我不确定在哪里传递自定义路由配置。
答案 0 :(得分:1)
虽然可能无法像在ASP.NET MVC中那样设置多个路由,但请尝试使用易于使用的注释来指定路由{。{3}}。
要启用属性路由,您需要在Register
方法中设置:
config.MapHttpAttributeRoutes();
这使您可以方便地为每种方法设置路线:
[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }
此外,Attribute Routing允许避免重复提供整个路径:
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
// GET api/books
[Route("")]
public IEnumerable<Book> Get() { ... }
// GET api/books/5
[Route("{id:int}")]
public Book Get(int id) { ... }
// POST api/books
[Route("")]
public HttpResponseMessage Post(Book book) { ... }
}
编辑回复你的评论:
看一下这个RoutePrefix
以及DefaultHttpControllerSelector
的派生方式,并填充一些逻辑:
public class ApiControllerSelector : DefaultHttpControllerSelector
{
public ApiControllerSelector (HttpConfiguration configuration) : base(configuration) { }
public override string GetControllerName(HttpRequestMessage request)
{
// add logic to remove hyphen from controller name lookup of the controller
return base.GetControllerName(request).Replace('-', string.Empty));
}
}
要使这项工作,您需要在配置中指定自定义ApiControllerSelector
,如下所示:
config.Services.Replace(typeof(IHttpControllerSelector),
new ApiControllerSelector(config));