简体   繁体   中英

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

When I try to add constructor,controller side says write constructor as a parameter. How Can i change interface to a constructor

You need to use

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

in order to dependency injection can inject your services.

If you want to uses interfaces via class constructor using DI,you need to pass the parameter with the same type from custom attribute on controller side.

To avoid doing that, you could register your interfaces as services and get them using below code without constructor injection.For example:

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 startup:

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

3.Custom Authorization Attribute

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM