Asp.net mvc 当ID包含句点时,ApiController返回404
我有一个ApiController,我想使用电子邮件地址作为请求的ID参数:Asp.net mvc 当ID包含句点时,ApiController返回404,asp.net-mvc,asp.net-web-api,asp.net-mvc-routing,Asp.net Mvc,Asp.net Web Api,Asp.net Mvc Routing,我有一个ApiController,我想使用电子邮件地址作为请求的ID参数: // GET api/employees/email@address.com public CompactEmployee Get(string id) { var email = id; return GetEmployeeByEmail(email); } 但是,我无法让它工作(返回404): http://localhost:1080/api/employees/employee@company.c
// GET api/employees/email@address.com
public CompactEmployee Get(string id) {
var email = id;
return GetEmployeeByEmail(email);
}
但是,我无法让它工作(返回404):
http://localhost:1080/api/employees/employee@company.com
以下是所有工作:
http://localhost:1080/api/employees/employee@公司
http://localhost:1080/api/employees/employee@公司。
http://localhost:1080/api/employees?id=employee@company.com
relaxedUrlToFileSystemMapping=“true”
设置为
我非常希望完整的电子邮件地址能够正常工作,但任何时候,只要在句点后加上任何其他字符,请求就会返回404。任何帮助都将不胜感激
解决方案
由于缺少其他选项,我选择了Maggie建议的方向,并使用中的答案创建了一个重写规则,以便在URL中需要电子邮件时自动附加一个尾随斜杠
<system.webServer>
....
<rewrite>
<rules>
<rule name="Add trailing slash" stopProcessing="true">
<match url="^(api/employees/.*\.[a-z]{2,4})$" />
<action type="Rewrite" url="{R:1}/" />
</rule>
</rules>
</rewrite>
</system.webServer>
....
添加尾部斜杠是否适用于您的场景
http://localhost:33021/api/employees/employee@company.com/
检查您的IIS设置:
主目录->配置
编辑.aspx
应用程序扩展名,并确保设置验证文件是否存在
已关闭
更新
我刚刚用一个默认的MVC4WebAPI项目进行了测试
URL:http://localhost:10983/api/values/cool@email.com
值控制器中的操作
:
public string Get(string id)
{
return id;
}
答复如下:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">cool@email.com</string>
cool@email.com
这就是我的工作原理:
我在targetFramework=4.6.1上运行。我已升级到4.6.2,并在web.config中添加了以下内容:
<system.web>
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.6.2"/>
<!-- This will allow to search for stuff that contains . & etc.-->
<httpRuntime targetFramework="4.6.2" maxRequestLength="100000" maxUrlLength="2048" relaxedUrlToFileSystemMapping="true" requestPathInvalidCharacters=""/>
</system.web>
requestPathInvalidCharacters=“”
当然可以在URI中以编码形式包含诸如&etc之类的内容。确实可以,但如果可能的话,希望避免这种情况。有人能快速写一下为什么添加斜杠会迫使Asp.net跳过尝试加载面向扩展资源的处理程序吗?解决了这个问题,但是我已经在一个服务器部署上获得了404,并且对于相同的代码库,从另一个部署获得了预期的响应。所以还有另一个潜在的配置问题,如果配置正确,后面的斜杠是不需要的。嗨,我很想知道你是否检查了这个,因为这在过去对我来说是个问题(老实说,只是好奇)。令人尴尬的是,没有。但我现在做到了(而且成功了,尽管我没想到会成功)。将更新我的答案。ThxAlso也看到了类似的问题:谢谢@Jonathan Freeland,这解决了我同样的问题。我摇摇头说微软认为这是一个好的设计。任何其他值得一试的web框架都可以让您使用regex或其他任何东西快速、轻松地配置静态/动态URL,而不是假设一个句点总是意味着一个静态文件,并让开发人员跳出障碍来绕过这一假设。真是不必要的时间浪费。谢谢@Jonathan Freeland!我当时的情况是,我无法更改客户端,但只需要在末尾添加该死的斜杠,您的解决方案对我来说非常有效