标签:als plain func imp summary for isp code context
声明一个自定义特性,继承自ActionFilterAttribute:
/// <summary>
/// 负责进行统一的权限检查
/// </summary>
public class CheckPermissAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//Session为空返回的登录
if (filterContext.HttpContext.Session[Keys.Uinfo] == null)
{
ToLogin(filterContext, "您未登录");
return;
}
//用户为空返回登录
sys_user userInfo = filterContext.HttpContext.Session[Keys.Uinfo] as sys_user;
if (userInfo == null || userInfo.bn_id <= 0)
{
ToLogin(filterContext, "您未登录");
return;
}
DBContext db = DapperDbContext.GetDbContext();
//获取控制器名称
string controllName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
//获取控制器方法名称
string actionName = filterContext.ActionDescriptor.ActionName;
string sql = "select DISTINCT m.mController,m.mAction,m.mName from sys_menus m INNER JOIN sys_permisslist p on m.mID=p.mID ";
sql += " INNER JOIN sys_userroler ur on p.rID = ur.RoleID and ur.uid =@uid ";
Dictionary<string, object> param = new Dictionary<string, object>();
param.Add("@uid", userInfo.bn_id);
var list = db.FindListBySql<sysmenus>(sql, param).ToList();
bool isPermiss = false;
//判断该用户是否包含该页面的访问权限
foreach (var item in list)
{
if (item.mController.Contains(controllName) && item.mAction.Contains(actionName))
{
isPermiss = true;
break;
}
}
if (!isPermiss)
{
ToLogin(filterContext, "您没有权限访问该页面");
return;
}
}
/// <summary>
/// 没有登录就跳转到登录
/// </summary>
/// <param name="filterContext"></param>
private static void ToLogin(ActionExecutingContext filterContext, string msg)
{
//获取当前action方法是否贴有AjaxRequest特性标签
bool isajax = filterContext.ActionDescriptor.IsDefined(typeof(AjaxRequestAttribute), false);
//表示截获的action方法是作为ajax来请求的
if (isajax)
{
//如果ajax请求则应该返回json
JsonResult json = new JsonResult();
json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
json.Data = new { status = StateTypeEnum.nologin, msg = msg, loginurl = "/Login/Login" };
filterContext.Result = json;
}
else
{
//如果是浏览器请求则直接将url跳转到登录页面即可
ContentResult content = new ContentResult();
content.Content = "<script>alert(‘"