V
V
Victor P.2020-09-18 17:29:45
ASP.NET
Victor P., 2020-09-18 17:29:45

Is it possible to make shorthand writing of .net core 3.1 filters?

Good afternoon!
I use .net core 3.1
I made a custom filter:

public class AuthorizeRoles : Attribute, IFilterFactory
    {
        public bool IsReusable => false;
        public RoleEnum[] roles { get; set; }

        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            var filter = serviceProvider.GetService(typeof(RolesValidation)) as RolesValidation;

            filter.roles = roles;

            return filter;
        }
    }


Now I can use it in some methods:
[HttpPost]
        [Route("[action]")]
        [AuthorizeRoles(roles = new RoleEnum[] { RoleEnum.roleManagement, RoleEnum.admin })]
        public async Task SetRoles([FromBody] UserAndRolesDto dto)
        {
            await service.SetRoles(dto.UserId, dto.Roles);
        }


The problem is that I would like to use an abbreviation, something like this:
[AuthorizeRoles(RoleEnum.roleManagement, RoleEnum.admin )]
//или даже
[Authorize(RoleEnum.roleManagement, RoleEnum.admin )]


Such a thing could be done in the .net framework, since it was possible to make a constructor with params RoleEnum[] roles, but it doesn’t work in .net core and I can’t find relevant information in the search engine

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
yuopi, 2020-09-18
@Jeer

Through the constructor works:

public class MyTestAttribute : Attribute
    {
        public MyEnum[] Roles { get; set; }

        public MyTestAttribute(params MyEnum[] roles)
        {
            Roles = roles;
        }
    }

Usage:
[MyTest(MyEnum.One, MyEnum.Three, MyEnum.Two, MyEnum.Two)]
public void SomeMethod() { }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question