zoukankan      html  css  js  c++  java
  • .NET Core MVC 登陆或权限过滤器

     1 using AuthorizationCenter.Define;
     2 using Microsoft.AspNetCore.Http;
     3 using Microsoft.AspNetCore.Mvc;
     4 using Microsoft.AspNetCore.Mvc.Controllers;
     5 using Microsoft.AspNetCore.Mvc.Filters;
     6 using System.Linq;
     7 
     8 namespace AuthorizationCenter.Filters
     9 {
    10     /// <summary>
    11     /// 登陆过滤器
    12     /// </summary>
    13     public class SignFilter : ActionFilterAttribute
    14     {
    15         /// <summary>
    16         /// 当动作执行中 
    17         /// </summary>
    18         /// <param name="context"></param>
    19         public override void OnActionExecuting(ActionExecutingContext context)
    20         {
    21             // 判断是否检查登陆
    22             var noNeedCheck = false;
    23             if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
    24             {
    25                 noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
    26                   .Any(a => a.GetType().Equals(typeof(NoSignAttribute)));
    27             }
    28             if (noNeedCheck) return;
    29 
    30             // 检查登陆 - 在SignIn中判断用户合法性,将登陆信息保存在Session中,在SignOut中移除登陆信息
    31             // 获取登陆信息 - 这里采用Session来保存登陆信息 -- Constants是字符串常量池
    32             var userid = context.HttpContext.Session.GetString(Constants.USERID);
    33             var signname = context.HttpContext.Session.GetString(Constants.SIGNNAME);
    34             var password = context.HttpContext.Session.GetString(Constants.PASSWORD);
    35 
    36             // 检查登陆信息
    37             if (userid == null && signname == null)
    38             {
    39                 // 用户未登陆 - 跳转到登陆界面
    40                 context.Result = new RedirectResult("/Sign/Index");
    41             }
    42             base.OnActionExecuting(context);
    43         }
    44     }
    45     /// <summary>
    46     /// 不需要登陆的地方加个特性
    47     /// </summary>
    48     public class NoSignAttribute : ActionFilterAttribute { }
    49 }

    不需要登陆的地方加个特性

    [NoSign]
    public IActionResult SignIn()
    {
        // TODO
    }

    需要注册过滤器

    1 public void ConfigureServices(IServiceCollection services)
    2 {
    3     services.AddMvc(config =>config.Filters.Add(typeof(SignFilter))).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    4     // Do Others
    5 }

    参考:
    .net core 登入全局验证过滤器
    Asp.net Core过滤器

  • 相关阅读:
    pam_smb
    什么是PAM认证
    如何使windows7的默认共享可以被访问[转载]
    remote mounting from windows to linux
    Kernel boot options
    Linux kernel启动选项(参数)
    tftp client命令示例
    在不同的Linux发行版上安装TFTP Server
    SpringBoot2 整合Nacos组件,环境搭建和入门案例详解
    我是如何做到springboot自动配置原理解析
  • 原文地址:https://www.cnblogs.com/amylis_chen/p/12316489.html
Copyright © 2011-2022 走看看