401上的自定义[授权]消息

时间:2017-02-21 21:48:18

标签: c# asp.net-web-api owin authorize

我需要提供自定义"未授权"不同语言的消息,而不是默认"此请求已拒绝授权"。我使用Owin作为身份验证,并使用ApiControllers / methods的[Authorize]属性。我知道这可以通过自定义自动化过滤器完成,但仅仅是为了更改发送到客户端的消息似乎是一种过度的情况。

是否有更简单的方法来更改消息,还是应该坚持使用自定义授权过滤器?

谢谢

1 个答案:

答案 0 :(得分:2)

不幸的是,这是不可能的。

基于source code,一个选项是创建一个新的自定义Authorize属性,继承自AuthorizeAttribute。然后,您只需要覆盖HandleUnauthorizedRequest方法,并替换为您自己的方法。其余的方法仍将由基础AuthorizeAttribute

处理
  public class MyCustomAuthAttribute : AuthorizeAttribute
  {
      protected virtual void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw Error.ArgumentNull("actionContext");
            }

                actionContext.Response =
                actionContext.ControllerContext.Request.CreateErrorResponse(
                                      HttpStatusCode.Unauthorized, 
                                      "My Un-Authorized Message");
      }
    } 
相关问题