asp.net-web-apiasp.net-web-api2http-status-code-411

WebAPI and status code 411 "Length Required"


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?


Solution

  • 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.

    Refer to this link for step by step implementation.