asp.net-core.net-coreaction-filter

ASP.NET Core 5 add action filter with parameter


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.


Solution

  • 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