最近公司再用.net core做项目。 碰到了登入验证权限这一块。使用过滤器不需要每个方法上都去判断登入是否失效。有的时候还会忘记对验证
希望对大家有帮助
mvc core的写法:
public class PermissionRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var isDefined = false;
var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
.Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)));
}
if (isDefined) return;
if (MyHttpContext.Current.Session.GetString("LoginInfo") == null)
{
filterContext.Result = new RedirectResult("/Account/Login");
}
base.OnActionExecuting(filterContext);
}
}
//不需要登入
public class NoPermissionRequiredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}
}
//在不需要的方法上面打上标记
[NoPermissionRequired]
public ActionResult Login()
{
}