401上的自定义[授权]消息 [英] Custom [Authorize] message on 401

查看:105
本文介绍了401上的自定义[授权]消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以不同的语言传递自定义的未经授权"消息,而不是默认的对此请求已拒绝授权".我将Owin用作身份验证,并将ApiControllers/方法的[Authorize]属性使用.我知道可以使用自定义自动过滤器来完成此操作,但是仅更改发送给客户端的消息似乎就显得过头了.

I need to deliver custom "not authorized" message in different languages, instead of the default "Authorization has been denied for this request". I'm using Owin as authentication and the [Authorize] attribute for ApiControllers/methods. I know that this could be done with a custom autorization filter, but it seems an overkill situation just to change the message sent to the client.

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

Is there a simpler way of changing the message or should I stick to a custom authorize filter?

谢谢

推荐答案

很遗憾,这是不可能的.

Unfortunately It is not possible.

基于源代码,一种选择是创建一个新的自定义Authorize属性,该属性继承自AuthorizeAttribute.然后,您只需要覆盖HandleUnauthorizedRequest方法,并用自己的方法替换即可.其余方法仍将由基本AuthorizeAttribute

Based on the source code, one option would be to create a new custom Authorize attribute, inheriting from AuthorizeAttribute. You then would only need to override the HandleUnauthorizedRequest method, and replace with your own. The rest of the methods would be still handled by the base 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");
      }
    } 

这篇关于401上的自定义[授权]消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆