有一个自定义的 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,这是预期的,但是reqeust仍然会遇到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");
?