我有一個AuthorizationHandler
,我想返回一個自定義的StatusCode(或文字),現在我只是想使它返回429(這是速率限制,但是這是不相關)AuthorizationPolicy設置狀態代碼
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
{
}
,你可以看到,我試圖設置狀態= 429 _accessor.HttpContext.Response.StatusCode = 429;
我一直在使用從var filterContext = context.Resource as AuthorizationFilterContext;
的HTTP上下文,然後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,除非我拋出一個異常。
我可以看到這是如何工作的,但我寧可不要從拋出一個異常,我的'處理程序'。讓我們看看別的進來 - 謝謝 –
當錯誤被募集'HandleRequirementAsync'全局事件過濾器不火。 –