一、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

原文地址:https://www.cnblogs.com/fger/p/11947332.html