【问题标题】:Web API Routing error from RC to RTM with model binding使用模型绑定从 RC 到 RTM 的 Web API 路由错误
【发布时间】:2012-08-30 22:02:59
【问题描述】:

将 rc 升级为 rtm web api 项目

简单类型参数的默认参数绑定现在是 [FromUri]:在以前版本的 ASP.NET Web API 中,简单类型参数的默认参数绑定使用模型绑定。简单类型参数的默认参数绑定现在是 [FromUri]。

我相信是让我感到厌烦的变化。

现在我不太确定。 StrathWeb 似乎让我觉得它应该按原样工作。

给定这个端点

   [HttpGet]
    public HttpResponseMessage Method(string a, string b)
    {
     ...
    }

我使用

在客户端生成一个 url
@Url.RouteUrl("route", new { httproute = "", controller = "Controller", version = "1" })">

让它生成这个路由的url。

routes.MapHttpRoute(
name: "route",
routeTemplate: "api/v{version}/{controller}/Method",
defaults: new
{
    action = "Method",
    controller = "Controller",
    version = "1"
});

它可以很好地创建 url。网址看起来像

.../api/v1/Controller/Method?optional=z
.../api/v1/Controller/Method?a=x&b=y&optional=z

请求时会抛出 404。如果我在api控制器中删除参数a和b,那么它就可以进入方法了。

进行这些绑定的正确方法是什么?

【问题讨论】:

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


    【解决方案1】:

    如果您需要 'a' 和 'b' 为可选参数,则需要将它们设为可选参数:

    公共 HttpResponseMessage 方法(字符串 a = null,字符串 b = null

    【讨论】:

    • 我之前试过这个,但是没有用。我一定是在这两者之间搞砸了,因为它现在起作用了。
    • 在路由中,您可以在默认部分中将 a 和 b 设置为 UrlParameter.Optional。我认为您不需要在方法中执行string a = null,因为string 默认情况下是可为空的类型?
    • 你可以做 UrlParameter.Optional 'if' 参数来自路由。如果它们来自查询字符串,我们需要说“string a = null”,即使它是可以为空的类型......这是对 RC 行为的改变......
    猜你喜欢
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2020-12-20
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多