Assuming you used the Identity tempate in .NET 7, simply add the "AddRole()" configuration as shown below.
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
In the controller used standard dependency injection.
public class RoleController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<IdentityUser> _userManager;
public RoleController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}
Then in the action simply invoke methods on the _roleManager.
// POST: RoleController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(string Name)
{
try
{
if (!string.IsNullOrEmpty(Name))
{
if (!(await _roleManager.RoleExistsAsync(Name)))
{
await _roleManager.CreateAsync(new IdentityRole(Name));
return RedirectToAction("Index");
}
}
return View();
}
catch
{
return View();
}
}
Create View
@model Microsoft.AspNetCore.Identity.IdentityRole
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<form method="post">
<input type="text" asp-for="Name" />
<input type="submit" name="submit" value="submit" />
</form>
If you are trying to seed a role when the application starts the see the Data Seeding reference documentation to access the role and user manager services.
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();
string role = "Manager";
if (!(await roleManager.RoleExistsAsync(role)))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}