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
You should be able to just check the length of body.
You can rely on Model binding As following
You can just check the
Form.Files
property of the request:Or bind to one of the special types –
IFormFile
,IEnumerable<IFormFile>
orIFormFileCollection
depending on the requirements:Check also: