1

I'm working on an ASP.NET hosted WebAPI endpoint for uploading files (multipart form-data). The expected files are going to be small so I'm going to leave the default max request size in place (4MB). When the request size is violated, by default the framework wants to return an HTML centric response. I'd like to return something more API client friendly.

Because of the way IIS and the ASP.NET pipeline works, request size violations do not appear to be handled by anything in the WebAPI pipeline such as MessageHandlers. Therefore, I've resorted to catching the error in the Global.asax.cs and redirecting to a controller which creates an API client friendly response.

protected void Application_Error()
{
    if (exception.Message.ToUpper().Contains("MAXIMUM REQUEST LENGTH"))
    {
        Server.ClearError();
        Response.Redirect("~/errors/500?message=" + exception.Message);
    }
}

public class ErrorsController : ApiController
{
   public HttpResponseMessage Get(int id, string message)
   {
      return Request.CreateResponse((HttpStatusCode)id, message);
   }
}

Is there a better way to do this? I'd love to be able to handle this sort of thing without issuing a 302 redirect.

4

1 回答 1

0

我到处寻找从 Application_Error 调用 API 控制器的方法,但找不到解决方案。

我得到的最接近的是下面。

但是,此代码会导致 System.Web.Http.DLL 中出现“System.NullReferenceException”。

我相信这是因为 HttpRequestMessage 不完整......它的 Headers 和 Properties 为空,但我不确定需要在那里做什么才能使其工作:

protected void Application_Error(object sender, EventArgs e){

        // Other code omitted for brevity

        Exception exception = Server.GetLastError();

        // Set the RouteData to point to the desired controller and action to invoke
        IHttpRouteData routeData = new HttpRouteData(new HttpRoute());
        routeData.Values.Add("controller", "Error");
        routeData.Values.Add("action", "Get");
        routeData.Values.Add("id", "500");
        routeData.Values.Add("message", exception.Message);

        // Avoid IIS7 returning its own stock error pages
        Response.TrySkipIisCustomErrors = true;

        // Call target Controller and pass the routeData.
        System.Web.Http.Controllers.IHttpController errorController = new ErrorController();
        var request = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri(Request.Url.AbsoluteUri),
        };

        errorController.ExecuteAsync(
            new HttpControllerContext(GlobalConfiguration.Configuration, routeData, request),
            CancellationToken.None
        );

TrySkipIisCustomErrors 参考:http ://www.west-wind.com/weblog/posts/2009/Apr/29/IIS-7-Error-Pages-taking-over-500-Errors

于 2013-02-21T14:18:26.300 回答