要創建自定義授權篩選器,您需要在解決方案中創建一個文件夾,並在其中添加一個名爲AuthorizedRoles.cs的文件。
AuthorizedRoles.cs文件爲:
sealed class AuthorizedRoles : ActionFilterAttribute
{
public string Roles { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var status = false;
string[] roles = Roles.Split(',');
var currentUserRole = Session.UserRole; // Get here the role of the user
var Role = "";
switch (currentUserRole)
{
case 1:
Role = "Role1";
break;
case 2:
Role = "Role2";
break;
case 3:
Role = "Role3";
break; // Check here for more role
default:
break;
}
if (Role != ""){
foreach (var role in roles)
{
if (role.Contains(currentRoleName))
{
status = true;
}
}
}
if (status == false)//That means user is not in the role, so redirect it to the new controller returning a view showing information that you are not autorized
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
//The request can be ajax callso it will redirect to another ajax method
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "ControllerName",
action = "AjaxActionName",
area = ""
}));
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
{
controller = "ControllerName",
action = "ActionName",
area = ""
}));
}
}
base.OnActionExecuting(filterContext);
}
}
重定向方法將像;
public ActionResult ActionName()
{
return View(); //Create view for this action
}
public JsonResult AjaxActionName()
{
return Json(new { status = false, message = "Unauthorized access." }, JsonRequestBehavior.AllowGet);
}
以上您要檢查的任何方法可以用來調用自定義授權過濾:
//This method will execute only if the user have Role1 and Role2 other wise redirected to other no permission methods before the action executes.
[AuthorizedRoles(Roles = "Role1,Role2")]
public ActionResult NeedPermissionAction(int id)
{
}