好的跟进 this thread ,这就是我想出的……
public class SharweAuthorizeAttribute : AuthorizeAttribute
{
private bool isAuthenticated = false;
private bool isAuthorized = false;
public new string[] Roles { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (SessionManager.CheckSession(SessionKeys.User) == true)
{
isAuthenticated = true;
foreach (string role in Roles)
{
if (RolesService.HasRole((string)role))
isAuthorized = true;
}
}
return (isAuthenticated && isAuthorized);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!isAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "User" },
{ "controller", "Login" }
});
} else if(!isAuthorized) {
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary
{
{ "action", "Home" },
{ "controller", "Error" }
});
}
}
}
我是如何/为什么想出这个的?因为我相信 AuthorizeAttribute 工作流程如下:
new
关键字来覆盖属性。因此,这就是我覆盖 Roles 属性的方式。但是,如果覆盖属性与初始属性(基类中的那个)属于不同类型,那是否也会隐藏它或创建一个完全不同的属性呢? 所以你怎么看?这真的应该奏效吗?我现在无法测试,因为我还没有设置UI(等待设计师完成设计)...... 其实这是我第一次体会到TDD的好处,我以前认为它是彻头彻尾的愚蠢而无用,但我错了:)
P.S:在 this thread ,@tvanfosson 正在设置上下文的 CachePolicy(我认为),有人可以解释一下,为什么我可能需要这样做吗?
提前致谢。
最佳答案
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private readonly bool _authorize;
private readonly string[] _roles;
public CustomAuthorizeAttribute(string roles)
{
_authorize = true;
_roles = roles.Split(',');
}
public CustomAuthorizeAttribute(string roles, bool isAdminPath)
{
_authorize = true;
_roles = roles.Split(',');
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//if controller have role auth and user is not loged
if(_authorize && !httpContext.User.Identity.IsAuthenticated)
return false;
// if controller have role auth and user is loged
if(_roles != null)
{
//grab user roles from DB
var UserRole = RoleRepository.GetUserRole(new Guid(httpContext.User.Identity.Name));
if (_roles.Contains(UserRole))
return true;
}
return false;
}
}
在 Controller 中
[CustomAuthorize("Administrator,Company,OtherRole")]
public ActionResult Test(){
return View();
}
关于asp.net-mvc - 自定义授权属性(后续),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5082951/