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

35

我有一个WebApi控制器,其中一个方法看起来像这样:

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

我有一个专门为此操作配置的自定义路由。当我在浏览器中导航到Web服务时,一切都正常,并执行适当的操作:

http://localhost:xxxx/ControllerName/Run/asdf/1/asdf/07-01-2012/user@domain.com

然而,当我尝试使用HttpClient程序化调用Web服务并执行"Get"时,如果用户名参数是电子邮件地址,我会收到404错误。例如,当用户名只是"user"时,一切正常。以下是示例代码:

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();

我尝试使用UrlEncoding对电子邮件地址进行编码,但没有成功。感谢任何建议。


尝试用 %40 替换 @,-编辑-这只是一个完全随意的猜测。-编辑2-UrlEncoding 应该已经为您切换了,如果我告诉您可以工作,您可能需要检查一下如何使用 UrlEncoding 和可能的参数。 - Pluc
2
考虑到您的请求的复杂性,您可能希望使用 POST 动词并发送自定义复杂对象。这样,您还可以跳过其他一些问题,例如无法在任何字符串中传递字符 / - user1908061
@user1908061 如果可能的话,我想保持使用 GET 方法,因为这样更容易通过浏览器进行测试。 - Matt Wolin
1
@MattWolin 浏览器测试 REST API 真的不应该是你的重点。相反,最好使用单元测试。如果您需要手动测试某些内容,只需使用 Fiddler 或浏览器插件提交请求即可。 - user1908061
5
也许有点晚了,但对我来说,在URL结尾加上斜杠“/”是有效的。
  • https://localhost:xxxx/user@domain.com 不起作用。
  • https://localhost:xxxx/user@domain.com/ 起作用。
- percebus
显示剩余3条评论
4个回答

40

我的一个快速想法是...是否.com导致了问题?


29
哇,谢谢!实际上是 '.' 符号引起了问题,而不是 '@' 符号。看到这篇帖子后:https://dev59.com/d2Yr5IYBdhLWcg3w6eM3我只需在路径中的最后一个参数后面添加一个斜杠 '/',就像魔术般地解决了问题。 - Matt Wolin

22

这是我认为我们会采用的修复方法,尽管我想看看是否会因此出现其他问题。 - Codeacula
@Codeacula 最差的性能是由于托管模块用于提供静态内容。如果内容需要任何类型的身份验证,这将是一件好事。 - user2320464

1

你需要一个基本的URL查询。

[Route("api/emails")]
public HttpResponseMessage Run(string email) {...}

GET api/emails?email=user@domain.com

1
将以下内容添加到web.config文件中不应该完全解决问题:
<system.webServer>  
     <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

The solution no longer works as an extra path segment is used in the uri for me. https://localhost:xxxx/user@domain.com does work

https://localhost:xxxx/path/user@domain.com does not work

I google around and around and i understood that it is an extension. (.cs gives a different error as .com) and finaly find this: ASP.net MVC4 WebApi route with file-name in it

My solution was to add or change the following handler in the <handlers> section of your <system.webServer>:

<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" 
           path="*.*" 
           verb="*" 
           type="System.Web.Handlers.TransferRequestHandler" 
           preCondition="integratedMode,runtimeVersionv4.0" />

or change the path to path=*@*.*


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接