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.