【问题标题】:Simple ASP.NET WebApi Parameter Binding Not Working简单的 ASP.NET WebApi 参数绑定不起作用
【发布时间】:2012-12-08 23:39:41
【问题描述】:

我很困惑为什么这适用于我的开发服务器(使用 IIS Express)而不是生产服务器(Win2K8 R2 + IIS 7.5)。

我有一个非常简单的 WebAPI 控制器方法:

 public HttpResponseMessage Get(string notificationType = "all", int skip=0, int take=25) {
        Trace.WriteLine(String.Format("Hello, world! From NotifcationsController#Get notificationType={0} skip={1} take={2}", notificationType, skip, take));   
        Trace.WriteLine(String.Format("And furthermore, HttpContext.Current.Request[notificationType]={0}", HttpContext.Current.Request["notificationType"]));
        Trace.WriteLine(String.Format("And finally, HttpContext.Current.Request.QueryString[notificationType]={0}", HttpContext.Current.Request.QueryString["notificationType"]));
      ...
 }

http://localhost:1398/api/notifications?notificationType=comments 的开发服务器上,一切正常。我在 trace.axd 中看到了这一点:

 Trace Information
 Category   Message From First(s)   From Last(s)
 Hello, world! From NotifcationsController#Get notificationType=comments skip=0 take=25     
 And furthermore, HttpContext.Current.Request[notificationType]=comments
 And finally, HttpContext.Current.Request.QueryString[notificationType]=comments

但是当我在http://api.nameofmywebsite.com/api/notifications?type=comments 上点击这个控制器时,我在 trace.axd 中看到了这个:

 Trace Information
 Category   Message From First(s)   From Last(s)
 Hello, world! From NotifcationsController#Get notificationType=all skip=0 take=25
 And furthermore, HttpContext.Current.Request[notificationType]=    
 And finally, HttpContext.Current.Request.QueryString[notificationType]=

 ...

 Querystring Collection
 Name   Value
 type   comments

这对我来说似乎非常非常奇怪。根据 trace.axd 中的内容,它似乎肯定不是路由问题……它击中了正确的控制器和操作。

为什么生产环境中查询字符串参数没有映射到控制器动作的参数!?

无论如何,我在开发和服务器上都使用相同的 web.config。我想不出什么配置差异会导致这种差异......

【问题讨论】:

    标签: asp.net-web-api


    【解决方案1】:

    我是个白痴。

    这不起作用,因为我在生产服务器上点击“notifications?type=cmets”而不是“notifications?notificationType=cmets”

    方法参数名称必须与查询字符串参数名称匹配才能进行绑定。我知道,但没有意识到我传入了错误的查询字符串参数名称!发生的事情是我几周前更改了方法参数名称,同时忘记了它,并且没有意识到浏览器的自动完成功能为我提供了包含旧参数名称的历史匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多