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

时间:2019-11-13 13:26:49

标签: c# asp.net-core .net-core-3.0

  

没有给出与'AuthorizeUserAttribute.AuthorizeUserAttribute(string,IUserRoleService,IModuleService,IUserService)'的必需形式参数'userRoleService'相对应的参数

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

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

2 个答案:

答案 0 :(得分:1)

您需要使用

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

为了进行依赖注入可以注入您的服务。

答案 1 :(得分:0)

如果要通过使用DI的类构造函数使用接口,则需要从控制器端的custom属性传递具有相同类型的参数。

为避免这样做,您可以将接口注册为服务,并使用以下代码获取它们,而无需构造函数注入。例如:

1。接口

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。启动时:

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

3。自定义授权属性

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。动作

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