【问题标题】:In ASP.Net WebAPI does RouteParameter.Optional mean optional part of the URL?在 ASP.Net WebAPI 中,RouteParameter.Optional 是否意味着 URL 的可选部分?
【发布时间】:2013-10-03 07:24:24
【问题描述】:

我有以下路由规则:

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

还有一个具有这些操作的 ProductController:

public Product Get(int id)
{
    return _svc.GetProduct(id);
}

public int Post(Product p)
{
   return 0;            
}

我可以按预期调用Get 操作:GET "api/product/2"

我认为我可以像这样调用我的 Post 操作:POST "api/product" 但它不起作用。我收到 404 错误。如果我这样做,它会起作用:POST "api/product/2"

我认为通过将 id RouteParameter.Optional 设为默认值,这意味着不需要存在 url 的 {id} 部分来匹配路由规则。但这似乎没有发生。是唯一的方法来制定另一个没有 {id} 部分的规则吗?

我有点困惑。感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    我认为它没有按预期工作,因为您正在向 id 参数添加约束。有关相同场景,请参阅此博客文章 http://james.boelen.ca/programming/webapi-routes-optional-parameters-constraints/

    更新: 看起来好像原来的链接已经死了,但是返回机器已经覆盖了我们: https://web.archive.org/web/20160228013349/http://james.boelen.ca/programming/webapi-routes-optional-parameters-constraints/

    【讨论】:

    • 您提供的网址给出了 403。请考虑更新您的答案。
    【解决方案2】:

    您需要将 id 设为可为空的 int 默认为 null

    // doesn't work
    public Product Get(int? id)
    {
        return _svc.GetProduct(id);
    }
    
    // works
    public Product Get(int? id = null)
    {
        return _svc.GetProduct(id);
    }
    

    我大约 95% 的把握这两个都在 MVC 下工作(当为路由参数声明 Optional 时),但 Web API 更严格。

    【讨论】:

    • 是的 - 我也很惊讶 :-)
    • 经过一番思考,我觉得这是有道理的。假设你有Get(int id, int? sometihng),所以你不能只用一个参数调用Get(1),所以这就是你必须指定默认值的原因.
    猜你喜欢
    • 1970-01-01
    • 2015-03-12
    • 2020-07-29
    • 2010-09-07
    • 2017-07-11
    • 2016-05-13
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多