[英]Is there a way to make AuthorizeAttribute respond with status code 403 Forbidden rather than a redirect?
If the user is not logged in and they request an action marked [Authorize]
, then the response is a redirect to the Account/LogOn action (status code 302 Found). 如果用户未登录并且他们请求标记为[Authorize]
,则响应是重定向到帐户/登录操作(状态代码302 Found)。
Is there a way to make the response be status code 403 Forbidden instead? 有没有办法让响应成为状态代码403 Forbidden?
Create an action filter that inherits from AuthorizeAttribute
. 创建一个继承自AuthorizeAttribute
的操作筛选器。 Then override this method: 然后覆盖此方法:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
Response.StatusCode = 403;
Response.Status = "Forbidden";
Response.StatusDescription = "Forbidden";
Response.End();
Response.Close();
}
If the user is not logged in then the more appropriate status code is 401:Unauthorized. 如果用户未登录,则更合适的状态代码为401:未授权。 This is what the AuthorizeAttribute returns by default. 这是AuthorizeAttribute默认返回的内容。
FormsAuthenticationModule will catch this return code and convert it into the redirect. FormsAuthenticationModule将捕获此返回代码并将其转换为重定向。 If you can disable (or not even load it) then this will be returned to the caller. 如果您可以禁用(或甚至不加载它),那么这将返回给调用者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.