【问题标题】:ApiController returns 404 when ID contains period当 ID 包含句点时,ApiController 返回 404
【发布时间】:2012-10-29 05:02:52
【问题描述】:

我有一个 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.com

以下所有工作:

  • http://localhost:1080/api/employees/employee@company
  • http://localhost:1080/api/employees/employee@company.
  • http://localhost:1080/api/employees?id=employee@company.com

我在 web.config 中将relaxedUrlToFileSystemMapping="true" 设置为detailed by Phil Haack

我非常希望完整的电子邮件地址能够正常工作,但只要句号后面跟着任何其他字符,请求就会返回 404。任何帮助将不胜感激!

解决方案

由于缺少其他选项,我已按照 Maggie 建议的方向前进,并使用来自 this question 的答案创建了一个重写规则,以便在我需要在 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>

【问题讨论】:

  • 谢谢@Jonathan-Freeland,这解决了我同样的问题。微软认为这是一个很好的设计,我只能摇头。任何其他值得一提的 Web 框架都可以让您使用正则表达式或 anything 快速轻松地配置静态/动态 URL,而不是假设句点始终意味着静态文件并导致开发人员跳过箍来解决问题这个假设。多么不必要的浪费时间。
  • 感谢@Jonathan-Freeland!我处于无法更改客户端但只需要在最后添加斜杠的情况下,您的解决方案对我来说非常有效

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


【解决方案1】:

在您的场景中添加斜杠是否有效?

http://localhost:33021/api/employees/employee@company.com/

【讨论】:

  • 确实如此,但如果可能的话希望避免这种情况。
  • 谁能快速写下为什么添加斜线强制 Asp.net 跳过试图加载面向扩展的资源的处理程序?
  • 确实解决了这个问题,但我在一台服务器部署上得到了 404,并且从另一个部署中得到了相同代码库的预期响应。因此还有另一个底层配置问题,如果配置正确,则不需要尾部斜杠。
【解决方案2】:

检查您的 IIS 设置:

Home Directory -&gt; Configuration

编辑.aspx 应用程序扩展并确保设置Verify that file exists 处于关闭状态。

更新

我刚刚使用默认的 MVC4 Web API 项目进行了测试

网址:http://localhost:10983/api/values/cool@email.com

ValuesController 中的操作:

public string Get(string id)
{
    return id;
}

这是回复:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">cool@email.com</string>

【讨论】:

  • 嗨,我很想知道你是否检查过这个,因为这对我来说是一个问题(老实说 - 只是好奇)。谢谢。
  • 尴尬的是没有。但我现在有了(它奏效了,虽然我没想到它会这样)。将更新我的答案。谢谢
【解决方案3】:

这对我有用:

我在 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 中以编码形式包含 & 等内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2014-03-04
    • 2010-10-10
    • 2011-05-09
    相关资源
    最近更新 更多