我有以下用于动态角色分配的自定义类:
public class DynamicAuthorizeAttribute : AuthorizeAttribute
{
IVRControlPanelRepository repository = new IVRControlPanelRepository();
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var controllerName = httpContext.Request.RequestContext.RouteData.Values["controller"];
var actionName = httpContext.Request.RequestContext.RouteData.Values["action"];
string controller = controllerName.ToString() + "Controller";
string action = actionName.ToString();
repository.GetAssignRole(controller, action);
GetRolesFromDatabase(controllerName, actionName);
// Roles = "Role1,Role2,Role3";
Roles = repository.GetAssignRole(controller, action);
return base.AuthorizeCore(httpContext);
}
}
以下是返回用逗号分隔的角色字符串的函数
public string GetAssignRole(string controllername, string actionname)
{
using (AppEntities db = new AppEntities())
{
var result = from u in db.AssignRoles where (u.ControllerName == controllername && u.ActionName == actionname) select u;
if (result.Count() != 0)
{
var rol = result.FirstOrDefault();
return rol.Role;
}
else
{
return "";
}
}
}
我已将属性放置[DynamicAuthorizeAttribute]
到所有控制器的所有操作中。
问题:
如果从 GetAssignRole() 返回的 Roles 为空,则将其重定向到 LogOn。Roles=""
但如果在上面的代码中,我实际上想指定为对操作的未经授权的访问。如果 Roles="Administrator,Member" 如果 Roles 是从 GetAssignRole() 返回的空字符串,则它可以正常工作。