.NET CoreMVC添加登录过滤器
1.添加過濾器類,繼承ActionFilterAttribute,在類里面添加過濾器方法
public override void OnActionExecuting(ActionExecutingContext context)
{
????????// 判斷是否檢查登錄
????????var noNeedCheck = false;
????????if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
????????{
????????????????noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true).Any(a => a.GetType().Equals(typeof(NoSignAttribute)));
????????}
????????if (noNeedCheck) return;
????????// 獲取登錄信息 - 這里采用Session來保存登錄信息
????????var UserName = context.HttpContext.Session.GetString("UserName");
????????// 檢查登錄信息
????????if (UserName == null)
????????{
????????????????// 用戶未登錄 - 跳轉到登錄界面
????????????????context.Result = new RedirectResult("/Login/Index");
????????}
????????base.OnActionExecuting(context);
}
?
2.添加不需要驗證登錄的特性,在不需要登陸的地方加個特性
public class NoSignAttribute : ActionFilterAttribute { }
3.在Startup類里面添加過濾器注冊
services.AddMvc(config => config.Filters.Add(typeof(SignFilter))).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
注:如果不需要驗證,即在不需要驗證的方法上面加入[NoSign]特性
總結
以上是生活随笔為你收集整理的.NET CoreMVC添加登录过滤器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高级软考考纲
- 下一篇: asp.net ajax控件工具集 Au