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");
}
}