本文介绍了如何从控制器调用构造函数中具有参数(接口)的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
{
}


推荐答案

它赚不了多少鉴于参数必须是编译时常量,对于属性就有意义。

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:

1.Interface:

public interface IUserService
{
   //..
}

public class UserService : IUserService
{
  //..
}

2。启动时:

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

3.Custom Authorization Attribute

3.Custom Authorization Attribute

public class HMACAuthenticationAttribute, IAsyncAuthorizationFilter
{

    public HMACAuthenticationAttribute()
    {

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

    }
}

更新:

另一种方式是您也可以使用 [ServiceFilter] [TypeFilter] 通过DI,请参阅

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

1。在启动时,注册 HMACAuthenticationAttribute

1.In startup, register HMACAuthenticationAttribute:

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

2.Custom Authorization Attribute

2.Custom Authorization Attribute

public class HMACAuthenticationAttribute, IAsyncAuthorizationFilter
{

    public HMACAuthenticationAttribute(IUserService user)
    {

    }

}

3.Controller

3.Controller

[ServiceFilter(typeof(HMACAuthenticationAttribute))]
public class WeatherForecastController : ControllerBase
{
}

这篇关于如何从控制器调用构造函数中具有参数(接口)的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 08:47