[英]Web API Routing {controller}/{action}/{id} vs default routing
I want to create a controller that can respond to those requests: 我想创建一个可以响应这些请求的控制器:
This is my actual code. 这是我的实际代码。
User Controller 用户控制器
public class UserController : ApiController
{
[HttpGet]
public IHttpActionResult Get(int id)
{
//... implementation...
}
[HttpGet]
[ActionName("UsersOfCompany")]
public IHttpActionResult UsersOfCompany(int id, [FromUri] Paging paging)
{
//... implementation...
}
[HttpGet]
[ActionName("AllowedCompanies")]
public IHttpActionResult AllowedCompanies(int id, [FromUri] Paging paging)
{
//... implementation...
}
}
WebApiConfig WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Servizi e configurazione dell'API Web
// Route dell'API Web
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ApiWithActionName",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MessageHandlers.Add(new LanguageMessageHandler());
}
}
RouteConfig 路由配置
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Based on sample request above, I would like routing work this way: 根据上面的示例请求,我希望以这种方式进行路由工作:
Get(int id)
UsersOfCompany(int id, [FromUri] Paging paging)
AllowedCompanies(int id, [FromUri] Paging paging)
But, now I can only call the last 2 requests (UsersOfCompany, AllowedCompanies). 但是,现在我只能调用最后两个请求(UsersOfCompany,AllowedCompanies)。 When I call api/User/123 I get this error: 当我调用api / User / 123时,出现此错误:
"Could not find an HTTP resource that matches the request's URL 'Service/api/User/123'.", "Unable to find an action on the 'User' controller with name '42887'." “无法找到与请求的URL'Service / api / User / 123'相匹配的HTTP资源。”,“无法在名称为'42887'的'User'控制器上找到操作。”
I already tried to invert the order of route registration but I otained the opposite behavior, so that api/User/123
call works and the others two not. 我已经尝试过反转路由注册的顺序,但是我得到了相反的行为,因此api/User/123
调用有效,而其他两个则不起作用。
Where's the problem? 哪里出问题了?
Your error message clearly states that WebApi tries to match Service/api/User/123
to the first pattern: api/{controller}/{action}/{id}
. 您的错误消息明确指出WebApi尝试将Service/api/User/123
与第一个模式匹配: api/{controller}/{action}/{id}
。
You could try to change order of registration in your WebApiConfig
or to specify the route explicitly: 您可以尝试更改WebApiConfig
的注册顺序或明确指定路由:
[Route("api/User/{id:int}")]
[HttpGet]
public IHttpActionResult Get(int id)
{
//... implementation...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.