Arash
Arash

Reputation: 4260

Unable to write to HttpContext's response body in asp.net core 2.1's middleware

Here it is our middleware's code snippet

public Task InvokeAsync(HttpContext context)
{
    if(!found)
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return context.Response.WriteAsync("Something wrong");
    }
    return _next(context);
}

The problem is that while the client app receives error code 401 which is fine but "Something wrong" string is not found in the response's body. What are we missing here?

Upvotes: 4

Views: 19548

Answers (4)

Torben Nielsen
Torben Nielsen

Reputation: 833

You should also set content-type. Something like this

    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
    context.Response.ContentType = "text/plain";
    return context.Response.WriteAsync("Something wrong");

Upvotes: 3

ˈvɔlə
ˈvɔlə

Reputation: 10242

The static and asynchronous method HttpResponseWritingExtensions.WriteAsync is currently the preferred way of reaching this goal.

Currently, you can find it in the assembly Assembly Microsoft.AspNetCore.Http.Abstractions.

using Microsoft.AspNetCore.Http;

public Task InvokeAsync(HttpContext context)
{
    if (found == false)
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        await HttpResponseWritingExtensions.WriteAsync(context.Response, "Something wrong");
    }
    return _next(context);
}

Upvotes: 2

Hamed Bagheri
Hamed Bagheri

Reputation: 1

you should use wait at the last of the Async function in this method:

HttpContext.Response.WriteAsync("Something wrong").Wait();

Reference: What's the difference between Task.Start/Wait and Async/Await?

Upvotes: 0

Arash
Arash

Reputation: 4260

An interesting solution that worked for us:

The following statement: return context.Response.WriteAsync("Something wrong");

was replaced by this one:

return context.Response.Body.WriteAsync("Something wrong").AsTask();

This change made the response be populated properly. Although, I'm not sure yet why this way of response body population would work but not the initial method.

Upvotes: 5

Related Questions