I have a custom middleware in my .NET Core 3.1 application, and trying to set the response StatusCode and Body like this:
public async Task Invoke(HttpContext context)
{
if ( <some condition on context.Request> )
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await context.Response.WriteAsync("my custom message");
// Bad request, do not call next middleware.
return;
}
// Call next middleware.
await _requestDelegate(context);
}
With the above code, the StatusCode is correctly set, however, the response Body is empty. How can I write my custom message to the Body?
Update1:
Added await
, but this won't solve the issue. Thanks @Jonesopolis for mentioning that.
Update 2
So I was testing the response in Swagger (I was also looking at the developer's Network tab). However, when I tested in Postman, I was getting the expected response body.
So the question really is why the response body wasn't showing up in Swagger/network tab?
Thanks!
await
on yourWriteAsync
line – Proficiencyawait
:( – Ganger