AuthorizationPolicy设置状态代码

时间:2017-05-23 13:10:04

标签: c# asp.net-mvc asp.net-core-mvc

我有一个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;

设置status = 429

我尝试使用var filterContext = context.Resource as AuthorizationFilterContext;filterContext.HttpContext

中的http上下文

我按照以下方式创建我的政策

services.AddSingleton<IAuthorizationHandler, ReCaptchaHandler>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthorization(options =>
{
    options.AddPolicy("ReCaptcha",
        policy => policy.Requirements.Add(new ReCaptchaRequirement()));
});

代码运行并保护标有[Authorize(Policy = "ReCaptcha")]的路由,但状态始终为400,除非我抛出异常。

2 个答案:

答案 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)

&lt; p&gt;假设您要覆盖API调用的异常代码,如果是这样,您是否尝试将新的异常过滤器添加到MVC配置过滤器,然后覆盖异常的状态代码,如下所示。&lt; / p&gt; &LT; p为H. Startup.cs&LT; / p为H. &lt; pre&gt;&lt; code&gt; services.AddMvc(options =&gt;             {                 options.Filters.Add(typeof运算(someExceptionFilter));             }) public class someExceptionFilter:IExceptionFilter     {         public someExceptionFilter()         {         }         public void OnException(ExceptionContext context)         {             var exceptionType = context.Exception.GetType();             if(exceptionType == typeof(yourException))             {                 context.ExceptionHandled = true;                 var response = context.HttpContext.Response;                 response.StatusCode = 429;                 response.ContentType =“application / json”;                 //response.WriteAsync(context.Exception.Message);                 context.Result = new JsonResult(context.Exception.Message);             }         }     } &LT; /代码&GT;&LT; /预&GT;