我有一个AuthorizationHandler
,我想立即返回一个自定义状态代码(或文本)我只是想让它返回429(这是为了速率限制,但这不相关)
public class ReCaptchaHandler : AuthorizationHandler<ReCaptchaRequirement>
{
private readonly ReCaptcha _reCaptcha;
private readonly IHttpContextAccessor _accessor;
public ReCaptchaHandler(ReCaptcha reCaptcha, IHttpContextAccessor accessor)
{
_reCaptcha = reCaptcha;
_accessor = accessor;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
ReCaptchaRequirement requirement)
{
context.Fail();
_accessor.HttpContext.Response.StatusCode = 429;
return Task.CompletedTask;
}
}
public class ReCaptchaRequirement : IAuthorizationRequirement
{
}
如您所见,我正在尝试使用_accessor.HttpContext.Response.StatusCode = 429;
我尝试使用var filterContext = context.Resource as AuthorizationFilterContext;
和filterContext.HttpContext
我按照以下方式创建我的政策
services.AddSingleton<IAuthorizationHandler, ReCaptchaHandler>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthorization(options =>
{
options.AddPolicy("ReCaptcha",
policy => policy.Requirements.Add(new ReCaptchaRequirement()));
});
代码运行并保护标有[Authorize(Policy = "ReCaptcha")]
的路由,但状态始终为400,除非我抛出异常。
答案 0 :(得分:3)
如果按照以下方式设置StatusCode
则可以
context.Fail();
var Response = filterContext.HttpContext.Response;
var message= Encoding.UTF8.GetBytes("ReCaptcha failed");
Response.OnStarting(async () =>
{
filterContext.HttpContext.Response.StatusCode = 429;
await Response.Body.WriteAsync(message, 0, message.Length);
});
答案 1 :(得分:1)