【发布时间】:2020-08-31 03:36:01
【问题描述】:
有一个自定义的AuthenticationHandler 命名为CustomAuthenticationHandler,默认错误码是401。但是我必须在不同的情况下用不同的错误码和错误信息来响应。
如果请求在某些情况下应该响应 403 并且当前的解决方案如下所示:
public class CustomAuthenticationHandler: AuthenticationHandler<MSGraphAuthenticationOptions>
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (xxx)
{
var response = this.httpContextAccessor.HttpContext.Response;
response.StatusCode = StatusCodes.Status403Forbidden;
await response.WriteAsync("test");
return AuthenticateResult.NoResult();
}
}
}
http 响应的错误代码是 403,这是预期的,但请求仍然会遇到 next() 并且会抛出错误:
System.InvalidOperationException: StatusCode cannot be set because the response has already started.
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ThrowResponseAlreadyStartedException(String name)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.Microsoft.AspNetCore.Http.Features.IHttpResponseFeature.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Http.DefaultHttpResponse.set_StatusCode(Int32 value)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.HandleChallengeAsync(AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.ChallengeAsync(AuthenticationProperties properties)
at Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, String scheme, AuthenticationProperties properties)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.Management.Services.CloudPC.Api.Middlewares.MetricsMiddleware.InvokeAsync(HttpContext context, ILoggerX logger)
如何在await response.WriteAsync("test"); 之后停止中间件流?
【问题讨论】:
-
您可以尝试通过
response.HasStarted检查“响应是否已经开始”。
标签: c# asp.net-core authentication asp.net-core-authenticationhandler