【问题标题】:WebApi action routesWebApi 动作路由
【发布时间】:2014-04-06 05:01:43
【问题描述】:

我试图在同一个控制器上支持多个 GET 请求,以便在模型上执行子操作,但是我无法让路由正常工作。我正在努力支持 -

/{controller}/{id}/{action}

虽然不踩默认

/{controller}/{id}

我尝试像这样创建另一个路由配置 -

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}/{action}"
        );

但是,这允许 /{controller}/{id}/{action} 处的路由,但 /{controller}/{id} 方法停止工作出现“发现多个操作”异常。

以下是我尝试公开的三种 GET 方法的示例-

    public HttpReponseMessage GetItem() 
    {

    }
    public HttpResponseMessage GetItem(int id)
    {

    }
    public HttpResponseMessage GetItemMetaData(int id)
    {

    }

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    如果您使用的是 Web API 2,请尝试使用 Attribute Routing,这样可以轻松处理此类情况。如果您仍在使用 Web API 1,请查看 Attribute Routing for Web API。如果由于某种原因您不想使用任何一种,您可以更详细地指定您的路线,如下所示:

    // Map your specific route first.
    config.Routes.MapHttpRoute(
        name: "NestedApi",
        routeTemplate: "api/{controller}/{id}/items",
        defaults: new{action = "GetItems"}
    );
    // You can have other specific routes here.
    
    // Map all other GET requests to a Get method.
    config.Routes.MapHttpRoute(
        name: "DefaultGetApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional, action = "Get" },
        constraints: new{httpMethod = new HttpMethodConstraint(HttpMethod.Get)}
    );
    
    // Use default route for all the rest.
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    

    【讨论】:

    • 这看起来很有希望。有点愚蠢的问题,但我可以判断我是否正在运行 WebAPI2?
    • @thebringking 我认为你可以检查 System.Web.Http,如果它是 5.0.0.0 或更高版本,那么你有 Web API 2,如果它更低,那么你有 Web API 1。
    • 谢谢,这对我有用。看起来我正在运行 WebAPI2,但该项目是 VS2012 项目。所以我没有 AttributeRouting。
    • 您实际上不需要 VS2013,您只需在新项目中默认获得 Web API 2。您还可以通过 NuGet 安装 Web API 2,它也可用于 VS2012。如果您有 Web API 2,请尝试将 Route 属性添加到操作方法并查看它是否有效。
    【解决方案2】:

    尝试在 SO 问题上使用此答案 Asp.Net Web API Routing not hitting custom action 作为起点。当我在我的应用程序中设计自定义路由时,它帮助了我很多。

    为了调试所有自定义路由,我默认使用ASP.NET Web API Route Debugger

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多