zoukankan      html  css  js  c++  java
  • 一、Core基于MVC的全局过滤器验证

    一、Core基于MVC的过滤器验证

    1、添加一个过滤器。在Startup 中ConfigureServices方法里添加一个Filters 即我们自己授权代码类。

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc(
                        options =>
                        {
                            options.Filters.Add<TestAttribute>(); //配置过滤器
                        }
                    ).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            }

    安全过滤器代码:

    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace Temp
    {
        //1、自定义特性 TestAttribute.cs
        public class TestAttribute : AuthorizeAttribute, IAuthorizationFilter
        {
            /// <summary>
            /// 重写实现处理授权失败时返回json,避免跳转登录页
            /// </summary>
    
            public TestAttribute()
            {
            }
    
            public void OnAuthorization(AuthorizationFilterContext context)
            {
                var user = context.HttpContext.User;
    
                if (!user.Identity.IsAuthenticated)
                {
                    context.Result = new JsonResult(value: new
                    {
                        success = false,
                        errs = new[] { "服务端拒绝访问:你没有权限,或者掉线了" }
                    });
                }
            }
    
        }
    }

     注意:必须继承ControllerBase

  • 相关阅读:
    mysql无法导出表内容
    mysql回收用户权限
    mysql跳过授权表进入服务
    数组forEach函数
    数组的filter函数
    无符号右移运算
    按位非运算符
    TP5页面跳转与重定向
    thinkphp5 $this->fetch()
    linux下vi命令修改文件及保存的使用方法
  • 原文地址:https://www.cnblogs.com/fger/p/11947332.html
Copyright © 2011-2022 走看看