skip to Main Content

What is the recommended and nice way to check if Request.Body is empty or not?

I have an API where there are different methods called when there is a file in the body of the request and different method when the body is empty.

[HttpPost]
public async void Post()
{
    var body = await new StreamReader(Request.Body).ReadToEndAsync();
    var contentLengthExists = Request.Headers.TryGetValue("content-length", out _);
    // This option
    // if(!string.IsNullOrEmpty(body))
    if(contentLengthExists)
    {
        // Do A
    }
    else
    {
        // Do B
    }            
}

I implemented two ways to check if there is a file in the body or not, but I am not sure this is the right way.

Option 1

var body = await new StreamReader(Request.Body).ReadToEndAsync();
if(!string.IsNullOrEmpty(body))

Option 2

var contentLengthExists = Request.Headers.TryGetValue("content-length", out _);
if(contentLengthExists)

Question

Is there any recommended or better way to check if the Request.Body contains something?

3

Answers


  1. You should be able to just check the length of body.

    var body = await new StreamReader(Request.Body).ReadToEndAsync();
    if(body.length == 0) {
      // Something
    } else {
     // Something else
    }
    
    Login or Signup to reply.
  2. You can rely on Model binding As following

    [HttpPost]
    public IActionResult Post(IFormFile? file)
    {
        if(file is null)
        {
            // Do A
            return BadRequest("No file to process");
        }
        // Do B
        return Ok("file recived!");
    }
    
    Login or Signup to reply.
  3. You can just check the Form.Files property of the request:

    if (Request.Form.Files.Any())
    {
                
    }
    

    Or bind to one of the special typesIFormFile, IEnumerable<IFormFile> or IFormFileCollection depending on the requirements:

    [HttpPost]
    public IActionResult Post(IFormFile? file)
    {
        if(file is null)
        {
            
        }
    }
    

    Check also:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search