【问题标题】:ASP.NET Web API application returns HTTP 500 for non existant routes with TransferRequestHandler enabledASP.NET Web API 应用程序在启用 TransferRequestHandler 的情况下为不存在的路由返回 HTTP 500
【发布时间】:2016-03-05 06:36:54
【问题描述】:

我创建了一个简单的 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" });
    }
}

现在我们需要在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>

现在的问题是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)

500 错误页面以 HTML 格式显示,应用程序日志中没有记录任何内容,也没有抛出异常。我正在使用带有 .NET 框架 4.5.1 的 VS 2015。

【问题讨论】:

  • 这个问题有什么解决办法吗?

标签: c# asp.net iis asp.net-web-api


【解决方案1】:

我也看到了这一点 - 我看到我的 global.asax.cs“BeginRequest”和“EndRequest”被调用了大约 10 次,用于此类请求。看起来像一个 ASP.NET/WebApi 错误。

我找到的解决方案是使用始终返回 404 的控制器注册“catch all”路由。

        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();
    }
}

【讨论】:

  • 有史以来最简单的解决方案!
猜你喜欢
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 2017-01-17
相关资源
最近更新 更多