简体   繁体   中英

ASP.NET Core MVC: can't add Admin Role

I'm currently unable to add an Admin role which will be mainly used to hide specific content from a regular users such as adding a new item to the site. This is because I'am getting an error whenever I try to go to the Admin create page.

在此处输入图像描述

This is my 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 page:

@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 code:

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?}");
                });
            }
        }
}

Here is a simple demo like below:

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

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