Cannot write to a HttpContext.Response in AuthenticationHandler

323 Views Asked by At

When in my custom AuthenticationHandler I want to write some data into HttpContext.Response like this:

protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
    await Context.Response.WriteAsJsonAsync(new SomeObject(), Context.RequestAborted);
    return AuthenticateResult.Fail("something went wrong");
}

I always get exception:

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1] An unhandled exception has occurred while executing the request. System.InvalidOperationException: StatusCode cannot be set because the response has already started.

With these stack traces:

at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ThrowResponseAlreadyStartedException(String value) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.set_StatusCode(Int32 value) at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.HandleChallengeAsync(AuthenticationProperties properties) at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.ChallengeAsync(AuthenticationProperties properties) at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties) at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.<>c__DisplayClass0_0.<g__Handle|0>d.MoveNext() --- End of stack trace from previous location ---

And:

at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context) at Microsoft.AspNetCore.Watch.BrowserRefresh.BrowserRefreshMiddleware.InvokeAsync(HttpContext context) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

Thought with this error my request is aborted and I don't get any response. If after writing to response I call Response.CompleteAsync() then exception is still thrown, but I get response.

Additionally, I don't have any custom middleware. How can I fix this?

0

There are 0 best solutions below