【问题标题】:Uri Path Extension Mapping in Web APIWeb API 中的 Uri 路径扩展映射
【发布时间】:2013-05-01 00:44:22
【问题描述】:

我正在尝试让 Uri 路径扩展映射在 Web API 中工作。我的路线设置正确:

routes.MapHttpRoute(
                       name: "Api with extension",
                       routeTemplate: "api/{controller}.{ext}/{id}",
                       defaults: new { id = RouteParameter.Optional, ext = RouteParameter.Optional }
                   );

routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );

它适用于默认路由,例如/api/products.json/123 但对于其他方法,例如/api/products.json?categoryid=5我收到一条错误消息:

"No action was found on the controller 'Products' that matches the request."

所有路由工作都没有扩展名,例如/api/products/123/api/products?categoryid=5。有人知道我缺少什么吗?

【问题讨论】:

  • 请您发布映射这两条路线的操作?
  • 它们会映射到:GetProduct(int id)GetProductsByCategory(int categoryid)

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


【解决方案1】:

如果其他人遇到这个问题,那么答案(如何让 Uri 扩展映射工作)可能如下(这对我自己有用,经过多次挫折和搜索)

将以下内容添加到您的 web.config 中的 System.WebServer 部分

<modules runAllManagedModulesForAllRequests="true"/>

【讨论】:

    【解决方案2】:

    /api/products.json?categoryid=5 将映射到以下控制器操作:

    public class ProductsController : ApiController
    {
        public string Get(int categoryid)
        {
            return categoryid.ToString();
        }
    }
    

    因此,请确保此控制器和操作存在。在 cmets 部分中,您似乎已经指出了一些 GetProduct(int id)GetProductsByCategory(int categoryid) 操作,但这些操作永远不会被使用。根据 RESTful 约定,当您使用 GET 动词时,将调用 Get 操作。如果您想使用一些非 RESTful 操作名称,请确保在路由定义中包含 {action}

    【讨论】:

    • 我的路线运行良好,只有当我尝试使用 UriPathExtensionMapping 时它们才会失败。据我了解,决定调用哪个操作的是 URI,因此 URI /api/products?categoryid=5 与操作 GetProductsById(int categoryid) 的签名相匹配所以呼叫被路由到那里。所有代码都基于本教程asp.net/web-api/overview/getting-started-with-aspnet-web-api/… 的一部分,并且在没有扩展的情况下也可以正常工作 - 只是我在工作时遇到了问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多