27: NET5 AOP-Filter extended customization

table of Contents

Permission background

Many functional pages developed; if there is no interception, there is no threshold;
come with a permission authentication; you can access it if you have permission, otherwise it will be rejected;
  1. Usually login
  2. Login with username + password (make a mark on the server or browser to record for the current)
  3. When accessing the page; verify whether you have logged in, you can also do some data verification through the current user information

Traditional authorization

Insert picture description here


Configure method, register


            app.UseAuthorization();//授权 检测有没有权限,是否能够访问后续的页面功能

ConfigureServices method (authentication and authorization)

             .AddCookie(options =>
                 options.LoginPath = new PathString("/Main/Login"); //如果授权失败,就跳转到这个路径去中
                 //options.AccessDeniedPath = new PathString("/Home/Privacy");

When authorizing: It is necessary to further go to the database to make some judgments based on the user's information; what to
Can support different roles and different strategies; I
'll talk about it in the next blog

Filter multiple registrations

  1. Bracket mark
  2. TypeFilter
  3. ServiceFilter
    can be placed on entity classes or methods.
    // 如果想要控制Filter的执行顺序怎么办?
    //使用typeFilter/ServiceFilter的时候可以执行Order;Order值越小 优先执行
    [ServiceFilter(typeof(ControllerActionFilterAttribute), Order = -1)]
    [TypeFilter(typeof(ControllerActionFilterAttribute), Order = -1)] //注册控制器
    [Authorize] ///第四步,表示当前Action 要支持鉴权授权

Extend Filter to support dependency injection

.NET5 Filter supports dependency injection

  1. TypeFilter
  2. ServiceFilter


    public class CustomFilterTypeAttribute : Attribute, IFilterFactory, IOrderedFilter
        private Type _Type = null;
        public CustomFilterTypeAttribute(Type type)
            this._Type = type;
        public bool IsReusable => true;

        public int Order => -1;

        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
            var rsult = (IFilterMetadata)serviceProvider.GetService(_Type);
            return rsult;

Filter execution characteristics

It is equivalent to a Russian matryoshka, from the outermost layer to the innermost layer, and then from the innermost layer to the outermost layer.

Insert picture description here