.NET Core MVC 登陆或权限过滤器

3 篇文章 0 订阅
2 篇文章 0 订阅

.NET Core MVC 登陆或权限过滤器

下面是登陆过滤器

using AuthorizationCenter.Define;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;

namespace AuthorizationCenter.Filters
{
    /// <summary>
    /// 登陆过滤器
    /// </summary>
    public class SignFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 当动作执行中 
        /// </summary>
        /// <param name="context"></param>
        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;

            // 检查登陆 - 在SignIn中判断用户合法性,将登陆信息保存在Session中,在SignOut中移除登陆信息
            // 获取登陆信息 - 这里采用Session来保存登陆信息 -- Constants是字符串常量池
            var userid = context.HttpContext.Session.GetString(Constants.USERID);
            var signname = context.HttpContext.Session.GetString(Constants.SIGNNAME);
            var password = context.HttpContext.Session.GetString(Constants.PASSWORD);

            // 检查登陆信息
            if (userid == null && signname == null)
            {
                // 用户未登陆 - 跳转到登陆界面
                context.Result = new RedirectResult("/Sign/Index");
            }
            base.OnActionExecuting(context);
        }
    }
    /// <summary>
    /// 不需要登陆的地方加个特性
    /// </summary>
    public class NoSignAttribute : ActionFilterAttribute { }
}

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

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

需要注册过滤器

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

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

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值