JianYA
JianYA

Reputation: 3024

ASP.NET Core 2.1 How to pass variables to TypeFilter

I have created this typefilter that is supposed to take 2 variables in order for it to send to a method that is linked to the filter. However, I am unable to attach my 2 variables for it to run.

public class RolesFilterAttribute : TypeFilterAttribute
{
    public RolesFilterAttribute() : base(typeof(RolesFilterAttributeImpl))
    {

    }

    private class RolesFilterAttributeImpl : IActionFilter
    {
        private readonly ValidateRoleClient validateRoleClient;
        private string Role;
        private string SecretKey;
        public RolesFilterAttributeImpl(string Role, string SecretKey, ValidateRoleClient validateRoleClient)
        {
            this.validateRoleClient = validateRoleClient;
            this.Role = Role;
            this.SecretKey = SecretKey;
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.HttpContext.Request.Cookies["Token"] != null || context.HttpContext.Request.Cookies["RefreshToken"] != null)
            {
                TokenViewModel tvm = new TokenViewModel
                {
                    Token = context.HttpContext.Request.Cookies["Token"],
                    RefreshToken = context.HttpContext.Request.Cookies["RefreshToken"]
                };
                ValidateRoleViewModel vrvm = new ValidateRoleViewModel
                {
                    Role = Role,
                    SecretKey = SecretKey,
                    Token = tvm
                };
                validateRoleClient.ValidateRole(vrvm);
            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            throw new NotImplementedException();
        }
    }
}

This is how I declare the filter and it compiles fine. However, I am not able to pass the required variables which are SecretKey and Role through it. Is my typefilter declared correctly?

[TypeFilter(typeof(RolesFilterAttribute))]
public IActionResult About()
{
    return View();
}

Upvotes: 3

Views: 3617

Answers (1)

Anton Toshik
Anton Toshik

Reputation: 2909

Taken from the official documentation

[TypeFilter(typeof(AddHeaderAttribute),
    Arguments = new object[] { "Author", "Steve Smith (@ardalis)" })]
public IActionResult Hi(string name)
{
    return Content($"Hi {name}");
}

Upvotes: 5

Related Questions