.net core 3.0 构造函数参数问题

.net core 3.0 Constructor parameter problem

There is no argument given that corresponds to the required formal parameter 'userRoleService' of 'AuthorizeUserAttribute.AuthorizeUserAttribute(string, IUserRoleService, IModuleService, IUserService)'

AuthorizationController.cs

[AuthorizeUserAttribute("User.Edit")]
public ActionResult UserAuthorizationEdit()

AuthorizeUserAttribute.cs

public string Action { get; set; }
private IUserRoleService _userRoleService;
private IModuleService _moduleService;
private IUserService _userService;

public AuthorizeUserAttribute(IUserRoleService userRoleService, IModuleService moduleService, IUserService userService)
{

    _userRoleService = userRoleService;
    _moduleService = moduleService;
    _userService = userService;
}

当我尝试添加构造函数时,控制器端说将构造函数写为参数。我如何将接口更改为构造函数

您需要使用

[TypeFileter(typeof(AuthorizeUser),Arguments = new object[] { "User.Edit" }))]
public ActionResult UserAuthorizationEdit(int userId, 
             RoleRegisterDto authorizationModel)

为了依赖注入可以注入你的服务。

如果你想通过 class 构造函数使用 DI 使用接口,你需要从控制器端的自定义属性传递相同类型的参数。

为避免这样做,您可以将您的接口注册为服务并使用下面的代码获取它们而不使用构造函数 injection.For 示例:

1.Interface

public interface IUserRoleService
{
    List<string> GetValues();
}

public class UserRoleService : IUserRoleService
{
    private List<string> _privateList = new List<string>();

    public List<string> GetValues()
    {
        _privateList.Add("test");
        return _privateList;
    }
}

2.In 启动:

public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton<IUserRoleService, UserRoleService>();
}

3.Custom授权属性

public class AuthorizeUserAttribute:AuthorizeAttribute, IAsyncAuthorizationFilter
{
    public string Action { get; set; }

    public AuthorizeUserAttribute(string action)
    {
        Action = action;       
    }
    public async Task OnAuthorizationAsync(AuthorizationFilterContext authorizationFilterContext)
    {
        var x = authorizationFilterContext.HttpContext.RequestServices.GetRequiredService<IUserRoleService>();
        var y = x.GetValues();
    }
}

4.Action

[AuthorizeUserAttribute("User.Edit")]
public ActionResult UserAuthorizationEdit()