ASP.NET MVC:自定义授权和MvcSiteMapProvider
本文关键字:授权 MvcSiteMapProvider 自定义 NET MVC ASP | 更新日期: 2023-09-27 17:59:53
在ASP.NET MVC中,我想以某种方式使用MvcSiteMapProvider进行自定义授权。
我知道我可以实现从AuthorizeAttribute继承的自定义Authorization Attribute。然后,我们也许可以用[SiteMapAuthorize]来装饰控制器。
这是最好的路线吗?如果是这样的话,我要寻找的是使用授权的站点地图提供商的正确实现。
public class SiteMapAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
}
}
谢谢你的帮助!
我有这个正在工作的
这是我的解决方案:
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工作:如何在ASP.NET MVC 2 中使用CustomErrors