.net mvc 登入全域性驗證過濾器
阿新 • • 發佈:2019-01-29
/// <summary>
/// 需要登入才能進行操作
/// </summary>
public class PermissionRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool result= filterContext.ActionDescriptor.IsDefined(typeof(NoPermissionRequiredAttribute), true);
if (result) return;
if (HttpContext.Current.Session["LoginName"]==null)
{
LogHelper.Info("未登入,跳轉到登入頁面");
//判斷是否是ajax提交
if (filterContext.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest")
{
//如果是ajax提交返回錯誤碼
HttpContext.Current.Response.StatusCode = 499;
}
else
{
filterContext.HttpContext.Response.Redirect("/Home/Login");
}
}
base.OnActionExecuting(filterContext);
}
/// 需要登入才能進行操作
/// </summary>
public class PermissionRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool result= filterContext.ActionDescriptor.IsDefined(typeof(NoPermissionRequiredAttribute), true);
if (result) return;
if (HttpContext.Current.Session["LoginName"]==null)
{
LogHelper.Info("未登入,跳轉到登入頁面");
//判斷是否是ajax提交
if (filterContext.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest")
{
//如果是ajax提交返回錯誤碼
HttpContext.Current.Response.StatusCode = 499;
}
else
{
filterContext.HttpContext.Response.Redirect("/Home/Login");
}
}
base.OnActionExecuting(filterContext);
}
}
//在不需要的方法上面打上標記
public class NoPermissionRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}
//全域性接收Ajax請求錯誤碼跳轉頁面
$.ajaxSetup({
statusCode: {
499: function () {
window.top.location.href = "/Account/Login";
}
}
});
//全域性定義過濾器
在Global中RegisterGlobalFilters加入
filters.Add(new PermissionRequiredAttribute());