[英]ASP.NET Web API application returns HTTP 500 for non existant routes with TransferRequestHandler enabled
I created a simple Web API app (empty template from Visual Studio with Web API enabled), added a controller: 我创建了一个简单的Web API应用程序(Visual Studio中启用了Web API的空模板),并添加了一个控制器:
[RoutePrefix("api/test")]
public class TestController : ApiController
{
[HttpGet]
[Route(@"resource/{*path?}")]
public async Task<HttpResponseMessage> GetFolder(string path = "")
{
return this.Request.CreateResponse(HttpStatusCode.OK, new { Status = "OK" });
}
}
Now we need to support file name extensions (eg file.pdf
) in the path
variable, so I modified the web.config: 现在我们需要在
path
变量中支持文件扩展名(例如file.pdf
),因此我修改了web.config:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<!-- API must handle all file names -->
<add name="ApiUrlHandler" path="/api/test/*" verb="GET,POST,PUT,DELETE,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
The problem now is that the HTTP status codes are inconsistents, depending on the URL segments provided after the prefix /api/test/
: 现在的问题是HTTP状态代码不一致,具体取决于前缀
/api/test/
后提供的URL段:
GET /api/test/resource => HTTP 200 (as expected)
GET /api/test/resource/foo => HTTP 200 (as expected)
GET /api/test/foo => HTTP 404 (as expected)
GET /api/test/foo/bar => HTTP 500 (expected: 404)
The 500 error page is displayed in HTML and nothing is logged in the application logs, no exception thrown. 500错误页面以HTML显示,并且应用程序日志中未记录任何内容,不会引发任何异常。 I am using VS 2015, with .NET framework 4.5.1.
我正在将VS 2015与.NET Framework 4.5.1一起使用。
I am seeing this as well - and I see that my global.asax.cs "BeginRequest" and "EndRequest" is called around 10 times for requests like these. 我也看到了这一点-而且我看到针对此类请求,我的global.asax.cs“ BeginRequest”和“ EndRequest”大约被调用了10次。 Looks like an ASP.NET/WebApi bug.
看起来像一个ASP.NET/WebApi错误。
The solution I found was to register a "catch all" route with a controller that always returns a 404. 我发现的解决方案是向始终返回404的控制器注册“全部捕获”路由。
config.Routes.MapHttpRoute(
name: "CatchAllRoute",
routeTemplate: "{*catchall}",
defaults: new { controller = "UnrecognizedRoute", action = ApiConstants.UnrecognizedRouteAction });
... ...
public class UnrecognizedRouteController : ApiController
{
/// <summary>
/// This method is called for every single API request that comes to the API and is not routed
/// </summary>
[ActionName(ApiConstants.UnrecognizedRouteAction)]
[HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPost, HttpPatch, HttpPut]
public IHttpActionResult ProcessUnrecognizedRoute()
{
return NotFound();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.