0
public class HMACAuthenticationAttribute : Attribute, IAsyncAuthorizationFilter
    {
       public HMACAuthenticationAttribute(IUser user)  
       {
         .....
       }
    }

Above code is attribute class and below code is controller. I want to call attribute with parameter

[HMACAuthentication()]
public class WeatherForecastController : ControllerBase
{
}

1 Answer 1

2

It doesn't make much sense for an attribute to accept interfaces, given that the arguments have to be compile-time constants.

One way is that you could register your interfaces as services and get them using below code without constructor injection.For example:

1.Interface:

public interface IUserService
{
   //..
}

public class UserService : IUserService
{
  //..
}

2.In startup:

public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IUserService, UserService>();
}

3.Custom Authorization Attribute

public class HMACAuthenticationAttribute, IAsyncAuthorizationFilter
{

    public HMACAuthenticationAttribute()
    {

    }
    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.RequestServices.GetRequiredService<IUserService>();

    }
}

Update:

Another way is that you could also use [ServiceFilter] or [TypeFilter] by DI,refer to

https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.1#servicefilterattribute

1.In startup, register HMACAuthenticationAttribute:

public void ConfigureServices(IServiceCollection services)
{
   services.AddScoped<HMACAuthenticationAttribute>();
   services.AddSingleton<IUserService, UserService>();
}

2.Custom Authorization Attribute

public class HMACAuthenticationAttribute, IAsyncAuthorizationFilter
{

    public HMACAuthenticationAttribute(IUserService user)
    {

    }

}

3.Controller

[ServiceFilter(typeof(HMACAuthenticationAttribute))]
public class WeatherForecastController : ControllerBase
{
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much you saved lot of time for me.

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.