ASP.NET Web API含小数点参数时返回404错误的解决求助
.NET Framework Web API路由含小数点返回404的解决方法
问题场景
环境:IIS 10.0、VS 2022、.NET Framework 4.7.2 Web API
接手的Web API应用1-2年前发布时完全正常,现在当参数包含小数点时,无论是本地IDE的IIS还是服务器IIS,都会返回404 Not Found。
测试代码示例:
[HttpPost] [Route("BatchData/ProcessResponseByString/{requestId}")] public HttpResponseMessage ProcessResponseByString(string requestId) { return new HttpResponseMessage() { Content = new StringContent($"String:{requestId}") }; } [HttpPost] [Route("BatchData/ProcessResponseByDouble/{requestId:double}")] public HttpResponseMessage ProcessResponse(double requestId) { return new HttpResponseMessage() { Content = new StringContent($"Double:{requestId}") }; }
- 可正常访问的URL:
https://localhost:44352/BatchData/ProcessResponseByString/12345https://localhost:44352/BatchData/ProcessResponseByDouble/12345
- 返回404的URL:
https://localhost:44352/BatchData/ProcessResponseByString/12345.67https://localhost:44352/BatchData/ProcessResponseByDouble/12345.67
解决方法
方法1:修改Web.config解除路径字符限制
在Web.config中添加以下配置,允许路径中的小数点和特殊字符:
- 在
<system.webServer>节点下配置请求筛选:
<system.webServer> <security> <requestFiltering allowDoubleEscaping="true"> <fileExtensions> <add fileExtension="." allowed="true" /> </fileExtensions> </requestFiltering> </security> </system.webServer>
- 在
<system.web>节点下配置请求路径验证:
<system.web> <httpRuntime requestValidationMode="2.0" requestPathInvalidCharacters="" /> </system.web>
注意:如果有安全需求,
requestPathInvalidCharacters可保留必要的非法字符,不要完全清空。
方法2:为路由添加显式约束
针对字符串参数的路由,通过正则约束明确允许小数点:
[HttpPost] [Route("BatchData/ProcessResponseByString/{requestId:regex(^[0-9.]+$)}")] public HttpResponseMessage ProcessResponseByString(string requestId) { return new HttpResponseMessage() { Content = new StringContent($"String:{requestId}") }; }
这种方式让路由引擎明确识别包含小数点的参数为有效路径段。
方法3:改用查询字符串传递参数
将参数从路径转移到查询字符串,避免路径字符限制:
[HttpPost] [Route("BatchData/ProcessResponseByString")] public HttpResponseMessage ProcessResponseByString([FromUri] string requestId) { return new HttpResponseMessage() { Content = new StringContent($"String:{requestId}") }; }
调用URL示例:https://localhost:44352/BatchData/ProcessResponseByString?requestId=12345.67
内容的提问来源于stack exchange,提问作者Douglas Marquardt
相关产品推荐
相关产品推荐

