我目前无法添加管理员角色,该角色主要用于向常规用户隐藏特定内容,例如向网站添加新项目。这是因为每当我尝试转到“管理员创建”页面时都会出现错误。
这是我的AdminController
:
public class AdminController : Controller
{
private readonly RoleManager<IdentityRole> _roleManager;
//public AdminController(RoleManager<IdentityRole> roleManager)
//{
// this.roleManager = roleManager;
//}
public AdminController(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager;
}
[HttpGet("admin/roles/create")]
public IActionResult CreateRole()
{
return View();
}
}
CreateRoleViewModel:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace JTMajorProject.DataAccess.Models
{
public class CreateRoleViewModel
{
[Required]
public string RoleName { get; set; }
}
}
CreateRole
页面:
@model JTMajorProject.DataAccess.Models.CreateRoleViewModel
@{
ViewData["Title"] = "Create a New Role";
}
<section class="about-banner relative">
<div class="overlay overlay-bg"></div>
<div class="container">
<div class="row d-flex align-items-center justify-content-center">
<div class="row">
<div class="col-md-10">
<h1 style="margin-top:120px; color: white;text-align:center;">@ViewData["Title"]</h1>
<form method="post">
<h4 style="color: white; text-align:center;">Create a new account.</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label style="color: white;" asp-for="RoleName"></label>
<input asp-for="RoleName" class="form-control" />
<span asp-validation-for="RoleName" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Create Role</button>
</form>
</div>
</div>
</div>
</div>
</section>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
STARTUP.CS
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JTMajorProject.DataAccess;
using JTMajorProject.DataAccess.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using JTMajorProject.Models;
using Microsoft.AspNetCore.Identity.UI;
namespace JTMajorProject
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// services.AddIdentity<JTMajorProject.DataAccess.Models.CreateRoleViewModel, IdentityRole>(options =>
// {
// options.User.RequireUniqueEmail = false;
// })
//.AddEntityFrameworkStores<Providers.Database.EFProvider.DataContext>()
//.AddDefaultTokenProviders();
// Connection string is still hard-coded
// Want to pull it from a configuration file
//options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=FileUploadDb;Trusted_Connection=True;ConnectRetryCount=0")
// Use the Configuration property to get the connection string
// Connection string is stored in appsettings.json
services.AddMvc();
services.AddDbContext<JTMajorProjectContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("JTMajorProjectContextConnection")));
// services.AddIdentity<IdentityUser, IdentityRole>(options =>
// {
// });//.AddEntityFrameworkStores<JTMajorProjectContext>();
//services.AddDefaultIdentity<IdentityUser>()
//.AddRoles<IdentityRole>()
//.AddEntityFrameworkStores<JTMajorProjectContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
答案 0 :(得分:1)
这是一个简单的演示,如下所示:
1.DbContext:
public class YourDbContext :IdentityDbContext
{
public YourDbContext(DbContextOptions<YourDbContext> options)
: base(options)
{
}
}
2.Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddIdentity<IdentityUser, IdentityRole>(cfg =>
{
cfg.User.RequireUniqueEmail = false;//optional
cfg.SignIn.RequireConfirmedEmail = false;//optional
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<YourDbContext>()
.AddDefaultTokenProviders();
services.AddDbContext<YourDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("YourConnectionstring")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
3.Controller:
[HttpGet("admin/roles/create")]
public IActionResult CreateRole()
{
return View();
}
[HttpPost("admin/roles/create")]
public async Task CreateRole(CreateRoleViewModel model)
{
var flag = _roleManager.RoleExistsAsync(model.RoleName);
// Check to see if Role Exists, if not create it
if (flag.Result==false)
{
var roleResult =await _roleManager.CreateAsync(new IdentityRole(model.RoleName));
}
}