I have a WEB API application, where we add some session verification logic and then call base SendAsync method after that.
When we pass request containing byte[] larger than 4MB line response = await base.SendAsync(request, cancellationToken);
throws a httpException "maximum request length exceeded", which is ok and can be managed through IIS settings. What bothers me is that next step - it's still calling controller method, where I can see that this byte[] parameter set to null. Controller method throws ArgumentNullException and this what end user gets.
First of all I can't understand why controller method still gets called after HttpException. And more important how can I manage to catch this HttpException, so that end user will see actual reason, why the request was not processed. Thank you in advance.
public class SessionIdHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
//some additional logic here
HttpResponseMessage response;
try
{
response = await base.SendAsync(request, cancellationToken);
}
catch (Exception e)
{
response = new HttpResponseMessage(HttpStatusCode.Forbidden)
{
Content = new StringContent(e.Message, Encoding.UTF8, "application/json")
};
}
finally
{
if (signedOnHere)
{
Signoff(sessionId);
}
}
return response;
}
}
When you call
base.SendAsync(request, cancellationToken);
, you're effectively continuing the WebAPI pipeline, which will eventually results in the controller getting invoked:What you actually want is to check the
Content-Length
header before you even send the request to the controller. You do so by retrieving it for the header of the request. If the size exceeds, you can return a response indicating that, otherwise, continue the pipeline:If you don't want this check for all the controllers in your WebAPI application, you can pre-route each
DelegatingHandler
.