WebAPI and status code 411 "Length Required"

2k Views Asked by At

411 Length Required The request did not specify the length of its content, which is required by the requested resource.

I have the following code:

    [HttpPost]
    [Route("UploadFileAsync/{RequestID}")]
    public async Task<HttpResponseMessage> UploadFileAsync(int RequestID)
    {
        SetUser();
        long maxAllowedFileSize = 9999999;


        long? contentLenght = Request.Content.Headers.ContentLength;

        if (!contentLenght.HasValue || contentLenght.Value > maxAllowedFileSize)
        {
            return Request.CreateErrorResponse(HttpStatusCode.LengthRequired, "Please set content lenght and file size should be less than 10 Mb");
        }

It works and return 411 status code when size of request is more than 9999999.

But I would like to validate it before uploading the whole request to server (as I understand, sense of this 411 status code to prevent uploading big files if server can't process it). How can I reject request and send 411 status code before sending the whole request to server?

1

There are 1 best solutions below

2
On BEST ANSWER

If you want to to validate the size before sending the request to Web API, then you need to do it at Web API client level.
However if you want to perform the validation before the Action in your web api controller is executed, you can use Action Filters. Typically, following steps are involved.

  • Create custom action filter for the Web API by inherting ActionFilterAttribute class.
  • Override OnActionExecuting method and write the code to check the content length and return appropriate error code within the method definition.
  • Register the custom filter in WebApiConfig file.
  • Decorate the action for which you want to apply this filter with your custom attribute

Refer to this link for step by step implementation.