2017-05-23 117 views
1

我有一個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,除非我拋出一個異常。

回答

1

如果設置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

假設你要覆蓋API調用異常代碼,如果是這樣,你有沒有嘗試添加一個新的異常過濾器MVC配置過濾器,然後覆蓋上的異常狀態的代碼,這樣的事情。

Startup.cs

services.AddMvc(options => 
      { 
       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); 
      } 
     } 
    } 
+0

我可以看到這是如何工作的,但我寧可不要從拋出一個異常,我的'處理程序'。讓我們看看別的進來 - 謝謝 –

+0

當錯誤被募集'HandleRequirementAsync'全局事件過濾器不火。 –