带有电子邮件地址参数的WebApi方法从HttpClient返回404

Mat*_*lin 31 c# asp.net asp.net-mvc-4 asp.net-web-api

我有一个WebApi控制器,其方法如下:

[HttpGet]
[AcceptVerbs("GET")]
public HttpResponseMessage Run(string reportName, int someId, string someText, DateTime asOfDate, string username)
Run Code Online (Sandbox Code Playgroud)

我有专门为此操作配置的自定义路由.当我将浏览器导航到Web服务时,一切正常,并执行相应的操作:

http://localhost:xxxx/ControllerName/Run/asdf/1/asdf/07-01-2012/user@domain.com
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用HttpClient以编程方式调用Web服务并执行"获取"时,我收到404错误.当username参数不是电子邮件地址时,我不会收到错误.例如,当用户名只是"用户"时,一切正常.以下是示例代码:

var url = "http://localhost:xxxx/ControllerName/Run/asdf/1/asdf/07-01-2012/user@domain.com"
var client = new System.Net.Http.HttpClient();
var response = client.Get(url);

//fails here with 404 error
response.EnsureSuccessStatusCode();
Run Code Online (Sandbox Code Playgroud)

我试过UrlEncoding电子邮件地址没有运气.任何建议表示赞赏.

Rya*_*tti 37

只是一个快速思考......".com"可能导致问题吗?

  • 哇谢谢!实际上是'.' 导致问题的字符,而不是'@'符号.看到这篇文章之后:http://stackoverflow.com/questions/13298542/apicontroller-returns-404-when-id-contains-period我刚刚在路由中添加了一个尾随'/'到最后一个参数,它就像一个魅力. (27认同)

小智 19

这是因为IIS正在尝试映射特殊字符.将以下内容添加到web.config应解决此问题:

<system.webServer>  
     <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

更多信息请访问:http://www.iis.net/configreference/system.webserver/modules