Web API 路由 {controller}/{action}/{id} 与默认路由

Web API Routing {controller}/{action}/{id} vs default routing

我想创建一个可以响应这些请求的控制器:

  1. api/User/123
  2. api/User/UsersOfCompany?id=123&pageIndex=0&pageSize=20
  3. api/User/AllowedCompanies?id=123&pageIndex=0&pageSize=10

这是我的实际代码。

用户控制器

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

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());
    }
}

路由配置

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 }
        );
    }
}

根据上面的示例请求,我希望路由以这种方式工作:

  1. Get(int id)
  2. UsersOfCompany(int id, [FromUri] Paging paging)
  3. AllowedCompanies(int id, [FromUri] Paging paging)

但是,现在我只能调用最后 2 个请求(UsersOfCompany、AllowedCompanies)。 当我调用 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'."

我已经尝试颠倒路由注册的顺序,但我得到了相反的行为,因此 api/User/123 调用有效而其他两个无效。

哪里出了问题?

您的错误消息清楚地指出 WebApi 尝试将 Service/api/User/123 匹配到第一个模式:api/{controller}/{action}/{id}.

您可以尝试更改 WebApiConfig 中的注册顺序或明确指定路线:

[Route("api/User/{id:int}")]
[HttpGet]
public IHttpActionResult Get(int id)
{
    //... implementation...
}