【发布时间】:2011-12-22 20:02:14
【问题描述】:
我完全被这个难住了。基本上,我有一个带有自定义 AuthorizeAttribute 的 MVC 页面,如果用户通过身份验证但没有适当的访问权限,则会引发 403 错误。我遇到的问题是我想将此错误重定向到自定义控制器/操作(/Error/Unauthorized)。
我在 web.config 中添加了以下内容
<httpErrors errorMode="Custom">
<remove statusCode ="403" subStatusCode="-1"/>
<error statusCode="403" path="/Error/Unauthorized" responseMode="ExecuteURL" />
</httpErrors>
通过上述配置,我看不到默认的 IIS 7.5 403 重定向。但是,我也没有看到任何东西。在 IE 中,它告诉我该网站需要您登录,而 chrome 只显示一个空白页面。
有什么想法吗?
这是自定义授权码,以防万一
public class CustomAuthorize : AuthorizeAttribute
{
//Property to allow array instead of single string.
private string[] _authorizedRoles;
public string[] AuthorizedRoles
{
get { return _authorizedRoles ?? new string[0]; }
set { _authorizedRoles = value; }
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
if (filterContext.HttpContext.Request.IsAuthenticated)
{
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.Result = new HttpStatusCodeResult(403);
}
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
if (!httpContext.User.Identity.IsAuthenticated)
return false;
//Check to see if any of the authorized roles fits into any assigned roles only if roles have been supplied.
if (AuthorizedRoles.Any(httpContext.User.IsInRole))
return true;
return false;
}
}
【问题讨论】:
-
好的,只是想尝试一些不同的场景,我将我的 customErrors 部分添加到 system.web 部分并尝试使用 404。在这种情况下,(由于我假设的 TrySkipIisCustomErrors) ,我发现我什至不需要 httpErrors 部分。但是,如果我尝试添加 403,页面仍然无法解析。这就是浏览器解释 403 的方式吗?他们不会允许重定向 403 吗?
标签: c# asp.net-mvc model-view-controller iis iis-7.5