如何从控制器调用构造函数中具有参数(接口)的属性 [英] How to call attribute which is having parameter(interface) in constructor from controller

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

问题描述

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.接口:

public interface IUserService
{
   //..
}

public class UserService : IUserService
{
  //..
}

2.启动时:

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

3.自定义授权属性

public class HMACAuthenticationAttribute, IAsyncAuthorizationFilter
{

    public HMACAuthenticationAttribute()
    {

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

    }
}

更新:

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

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

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

1.启动时注册HMACAuthenticationAttribute:

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

2.自定义授权属性

public class HMACAuthenticationAttribute, IAsyncAuthorizationFilter
{

    public HMACAuthenticationAttribute(IUserService user)
    {

    }

}

3.控制器

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆