【问题标题】:Routing in ASP .NET Web APIASP .NET Web API 中的路由
【发布时间】:2014-02-20 16:32:11
【问题描述】:

我使用 WEB API 创建了一个网络服务。

我正在使用这个路由配置

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

我的解决方案包括两个控制器(ProductControllerDetailController

所以当我想调用一个引用 GetDetails 方法的 WS(位于 DetailController 中)时,我必须使用这样的 URL:

http://localhost/api/Details/GetDetails/?id=4

有没有办法使用,对于同一个请求,这个 URL 来代替:

http://localhost/api/Product/GetDetails/?id=4

让 DetailController 中的 GetDetails 方法?

【问题讨论】:

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


    【解决方案1】:

    其实你的网址应该是:

    http://localhost/api/Details/4
    http://localhost/api/Products/4
    

    和你的控制器:

    public class DetailsController: ApiController
    {
        public HttpResponseMessage Get(int id)
        {
            ...
        }
    }
    

    和:

    public class ProductsController: ApiController
    {
        public HttpResponseMessage Get(int id)
        {
            ...
        }
    }
    

    现在是 RESTful。

    【讨论】:

    • 你能解释一下使用查询参数而不是url本身来表示资源的原因(即http://localhost/api/Details/4)。它看起来不像“RESTful”。
    • 你是对的。在这种情况下,拥有/{id} 会更漂亮。但这并不意味着查询字符串参数不是 RESTful。通常当我有可选参数时,我将它们作为查询字符串参数传递。这在需要采用多个参数的 GET 请求中通常是有意义的。但我同意你的观点,标识资源的标识符最好在路径部分中传递。
    • 不,我了解查询参数的用例。似乎 id(在这种情况下)旨在唯一地表示资源。
    • 完全同意你的看法。我已经更新了我的答案,以考虑您的评论。
    猜你喜欢
    • 2013-01-16
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 2019-05-30
    • 2019-08-06
    相关资源
    最近更新 更多