这是indexloc提供的服务,不要输入任何密码
Skip to content

Create Role #1308

@asgharb

Description

@asgharb

If I want to define a role and assign a role to a user, what is the procedure? In which layer should I define the interfaces and services?
this is my code in ((Application)):

`public class CreateRoleCommandHandler : IRequestHandler<CreateRoleCommand, bool>
{
private readonly IRoleService _roleService;

public CreateRoleCommandHandler(IRoleService roleService)
{
    _roleService = roleService;
}

public async Task<bool> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
{
    var roleExists = await _roleService.RoleExistsAsync(request.RoleName);

    if (roleExists)
    {
        throw new InvalidOperationException($"Role '{request.RoleName}' already exists.");
    }

    var result = await _roleService.CreateRoleAsync(request.RoleName);

    if (!result)
    {
        throw new Exception($"Failed to create role '{request.RoleName}'.");
    }

    return true;
}

}`

and my code in((Infrastructure)):

`public class RoleService : IRoleService
{
private readonly RoleManager _roleManager;

public RoleService(RoleManager<IdentityRole> roleManager)
{
    _roleManager = roleManager;
}

public async Task<bool> RoleExistsAsync(string roleName)
{
    return await _roleManager.RoleExistsAsync(roleName);
}

public async Task<bool> CreateRoleAsync(string roleName)
{
    var result = await _roleManager.CreateAsync(new IdentityRole(roleName));
    return result.Succeeded;
}

}`

Is my path and method correct?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions