IIS7.5 HttpErrors ExecuteURL没有执行

时间:2011-12-22 20:02:15

标签: c# asp.net-mvc model-view-controller iis iis-7.5

我对这一点感到非常难过。基本上,我有一个带有自定义AuthorizeAttribute的MVC页面,如果用户通过身份验证但没有适当的访问权限,则会抛出403错误。我遇到的问题是我想将此错误重定向到自定义控制器/操作(/错误/未授权)。

我在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;
        }
    }

1 个答案:

答案 0 :(得分:0)

好的,我不确定这是否真的正确,但它符合我的症状。 http://forums.asp.net/t/1462153.aspx/1 我不满意我必须对重定向进行编码,但我试图将其至少明确地用于将来的可维护性。

    public bool RedirectAuthenticatedButUnauthorizedUsers { get; set; }

    private String _redirectUnauthorizedUrl = String.Empty;
    public String RedirectUnauthorizedUrl
    {
        get { return _redirectUnauthorizedUrl; }
        set { _redirectUnauthorizedUrl = value.Trim(); }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        base.HandleUnauthorizedRequest(filterContext);
        if (!RedirectAuthenticatedButUnauthorizedUsers || !filterContext.HttpContext.Request.IsAuthenticated)
            return;
        if(RedirectUnauthorizedUrl == String.Empty)
            throw new NullReferenceException("RedirectAuthenticatedButUnauthorizedUsers " +
                                             "set to true, but no redirect URL set.");
        filterContext.HttpContext.Response.Redirect(RedirectUnauthorizedUrl);
    }