0

Trying to add an authentication filter to an ASP.NET Core 5 MVC action method and pass a parameter. However I'm unable to find a way to do this. This is the action filter code:

public class CheckUserPrivilege : IActionFilter
{
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ISession _session;
        public string PrivilegeCode { get; set; }

        public CheckUserPrivilledge(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            _session = _httpContextAccessor.HttpContext.Session;
        }
}

The parameter we need to pass is PrivilegeCode. Ideally want something like [CheckUserPrivilege("abc")] but when we try like so, I presume it also asks for the IHttpContextAccessor` parameter in the constructor.

Any help appreciated.

0

1 Answer 1

5

You don't need to use IHttpContextAccessor to get parameter , You just need to use the following code :

public class CheckUserFilter : Attribute,IActionFilter
    {
        
        private readonly string PrivilegeCode;
        public CheckUserFilter(string _PrivilegeCode)
        {
            PrivilegeCode = _PrivilegeCode;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //........
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            //If you want to do somthing about context,
           // you just need to use`context.HttpContext.....`

            
        }
    }

when you try [CheckUserPrivilege("abc")] ,you can get the value in filter

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. seems to do the job
More details can be found here, which include Core2 Core3 and core6 pending

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.