ASP.NET MVC:自定义授权和MvcSiteMapProvider

时间:2011-06-22 15:36:59

标签: c# asp.net-mvc sitemap

在ASP.NET MVC中,我想以某种方式使用MvcSiteMapProvider进行自定义授权。

我知道我可以实现一个继承自AuthorizeAttribute的自定义授权属性。然后,我们可以用[SiteMapAuthorize]来装饰控制器。

这是最好的路线吗?如果是这样,我正在寻找的是使用具有授权的站点地图提供程序的正确实现。

public class SiteMapAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {

    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我有这个工作

这是我的解决方案:

public class SiteMapAuthorizeAttribute : AuthorizeAttribute
{
    public string Action { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!httpContext.User.Identity.IsAuthenticated)
            return false;

        var node = SiteMap.CurrentNode;

        // If the node is null, then it was not loaded into memory 
        // because this user was not authorized to view this node
        if (node == null)
            return false;

        // Check the node's accessibility regardless in case we got passed the above check
        return node.IsAccessibleToUser(HttpContext.Current);
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        // If user is not authenticated allow default handling
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            base.HandleUnauthorizedRequest(filterContext);
            return;
        }

        string customErrorPage = GetCustomError("403");
        if (customErrorPage == null)
        {
            base.HandleUnauthorizedRequest(filterContext);
            return;
        }

        // Redirect to 403 (Access Denied) page
        filterContext.Result = new RedirectResult(customErrorPage);
    }

    private string GetCustomError(string statusCode)
    {
        CustomErrorsSection customErrorsSection = ConfigurationManager.GetSection("system.web/customErrors") as CustomErrorsSection;

        if (customErrorsSection != null)
        {
            CustomError customErrorPage = customErrorsSection.Errors[statusCode];

            if (customErrorPage != null)
                return customErrorPage.Redirect;
        }
        return null;
    }
}

HandleUnauthorizedRequest与web.config中的customErrors部分一起使用:

<customErrors mode="On" defaultRedirect="~/Error">
  <error statusCode="404" redirect="~/Error/NotFound"/>
  <error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>

您需要一个错误控制器才能使上述customErrors工作: How to use CustomErrors in ASP.NET MVC 2