WebApi代理为具有无效字符的URL抛出404

Aug*_*ves 9 c# asp.net-web-api asp.net-web-api-routing

我正在使用C#.NET WebApi来创建一个API代理,这里是我所拥有的基本代码,适用于大多数调用:

[HttpGet]
[Route("api/proxy/{*.}")]
public async Task<HttpResponseMessage> Get()
{
   // some route here...
}
Run Code Online (Sandbox Code Playgroud)

但是当我有一个带有特殊字符的URL,例如:(%3F)或/(%2F)时,它会失败并显示404.如果我删除了特殊字符,它就可以了.

http://localhost:3000/api/proxy/viewing/v1/items/urn%3Aadsk.viewing%3Afs.file%3AdXJuOmVUE_dmVyc2lvbj0x%2Foutput%2Fd4b6ef1c-8d219bd84c9d%2F0.pf?domain=http%3A%2F%2Flocalhost%3A3000
Run Code Online (Sandbox Code Playgroud)

并在web.config上尝试了一些建议,但没有:

<system.web>
  <httpRuntime targetFramework="4.6" requestPathInvalidCharacters=""/>
  <pages validateRequest="false" />
</system.web>
Run Code Online (Sandbox Code Playgroud)

所有其他WebApi端点都使用Global.asax,如下所示:

public class Global : System.Web.HttpApplication
{
  protected void Application_Start(object sender, EventArgs e)
  {
    GlobalConfiguration.Configure(Config.WebApiConfig.Register);
  }
}
Run Code Online (Sandbox Code Playgroud)

和Config.WebApiConfig:

public class WebApiConfig
{
  public static void Register(HttpConfiguration config)
  {
    config.MapHttpAttributeRoutes();
  }
}
Run Code Online (Sandbox Code Playgroud)

And*_*nov 5

根据答案,当url包含编码的&符号时,MVC WEB API路由失败,您需要从以下requestPathInvalidCharacters属性中删除您认为有效的字符httpruntime:

<httpruntime requestvalidationmode="2.0">
             requestPathInvalidCharacters="*,:,&amp;,\"
             relaxedUrlToFileSystemMapping="true" />
Run Code Online (Sandbox Code Playgroud)

但是将这些参数作为查询字符串传递更安全.

编辑:

我已经测试了你的问题网址http://localhost:3000/proxy/target/v1/urn%3Aparam%2Foutpu?domain=http%3A%2F%2Flocalhost%3A3000,它只是允许%字符.所以你需要在requestPathInvalidCharacters属性中列出允许的字符,ig : %,&amp;,*,\. 我目前的配置是:

<httpRuntime targetFramework="4.6.1" requestPathInvalidCharacters="%" />
Run Code Online (Sandbox Code Playgroud)

编辑2:

我做了一些研究,并找到了ASP.net MVC4 WebApi路由的答案,其中包含文件名.简单的解决方案是runAllManagedModulesForAllRequests在web配置中向模块部分添加属性.如果您检查已接受的答案,则可以尝试微调解决方案以减少运行所有托管模块的影响.

最后,您需要修改以下部分.我只删除:requestPathInvalidCharacters的默认值,该值适用于已解码的URL,与%编码的URL中的字符无关:

<system.web>
  <httpRuntime requestPathInvalidCharacters="&lt;,&gt;,*,%,&amp;,\,?"/>
</system.web>

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