简体   繁体   English

registration\Areas\Identity\Pages\Account\Register.cshtml(61,78,61,83):错误 CS0103:当前上下文中不存在名称“角色”

[英]registration\Areas\Identity\Pages\Account\Register.cshtml(61,78,61,83): error CS0103: The name 'roles' does not exist in the current context

I'm trying to build a registration system with roles to view data with limitations in my Asp.Net core project using Identity so I got this error and I'll appreciate it if someone guides me to solutions............................我正在尝试构建一个具有角色的注册系统,以使用 Identity 在我的 Asp.Net 核心项目中查看有限制的数据,所以我遇到了这个错误,如果有人指导我解决问题,我将不胜感激...... .....................

and registration\Areas\Identity\Pages\Account\Register.cshtml(61,78,61,83): error CS0103: The name 'roles' does not exist in the current context

Program.cs:程序.cs:

using login_and_registration.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using login_and_registration.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity.UI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("lAppregistrationContextConnection");
builder.Services.AddDbContext<lAppregistrationContext>(options =>
    options.UseSqlServer(connectionString));builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<loginregistrationUser>(options => {

    options.SignIn.RequireConfirmedAccount = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireUppercase = false;
    options.Password.RequireNonAlphanumeric = false;
})
    .AddRoles<IdentityRole>()
    .AddDefaultUI()
    .AddEntityFrameworkStores<lAppregistrationContext>();
    //.AddDefaultTokenProviders();

builder.Services.AddScoped<IUserClaimsPrincipalFactory<loginregistrationUser>,ApplicationUserClaims>();

builder.Services.AddControllersWithViews();

//builder.Services.AddTransient<IEmailSender, EmailSender>();
builder.Services.AddRazorPages();
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("lAppregistrationContextConnection")));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
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.UseRouting();

app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{


    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();

});

app.Run();

RoleController:角色控制器:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace login_and_registration.Controllers
{
    public class RoleController : Controller
    {
        //public IActionResult Index()
        //{
        //    return View();
        //}


        RoleManager<IdentityRole> roleManager;
        public RoleController(RoleManager<IdentityRole> roleManager)
        {
            this.roleManager = roleManager;
        }
        public IActionResult Index()
        {
            var roles = roleManager.Roles.ToList();
            return View(roles);
        }



        public IActionResult Create()
        {

            return View(new IdentityRole());
        }
        [HttpPost]
        public async Task<IActionResult> Create(IdentityRole role)
        {
            await roleManager.CreateAsync(role);
            return RedirectToAction("Index");
        }
    }
}

DbContext:数据库上下文:

using login_and_registration.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace login_and_registration.Areas.Identity.Data;

public class lAppregistrationContext : IdentityDbContext<loginregistrationUser>
{
    public lAppregistrationContext(DbContextOptions<lAppregistrationContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }


}

Register.cshtml:注册.cshtml:

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using login_and_registration.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;

namespace login_and_registration.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class RegisterModel : PageModel
    {
        private readonly SignInManager<loginregistrationUser> _signInManager;
        private readonly UserManager<loginregistrationUser> _userManager;
        private readonly IUserStore<loginregistrationUser> _userStore;
        private readonly IUserEmailStore<loginregistrationUser> _emailStore;
        private readonly ILogger<RegisterModel> _logger;
        private readonly IEmailSender _emailSender;
        private readonly RoleManager<IdentityRole> _roleManager;


        public RegisterModel(
            UserManager<loginregistrationUser> userManager,
            IUserStore<loginregistrationUser> userStore,
            SignInManager<loginregistrationUser> signInManager,
            ILogger<RegisterModel> logger,
            IEmailSender emailSender,
             RoleManager<IdentityRole> roleManager)
        {
            _userManager = userManager;
            _userStore = userStore;
            _emailStore = GetEmailStore();
            _signInManager = signInManager;
            _logger = logger;
            _emailSender = emailSender;
            _roleManager = roleManager;
        }

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        [BindProperty]
        public InputModel Input { get; set; }

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public string ReturnUrl { get; set; }

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        /// <summary>
        ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public class InputModel
        {
            /// <summary>
            ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
            ///     directly from your code. This API may change or be removed in future releases.
            /// </summary>
            /// 

            

            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "First Name")]
            public string FirstName { get; set; }

            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Last Name")]
            public string LastName { get; set; }



            [Required]
            [EmailAddress]
            [Display(Name = "Email")]
            public string Email { get; set; }

            /// <summary>
            ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
            ///     directly from your code. This API may change or be removed in future releases.
            /// </summary>
            [Required]
            [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string Password { get; set; }

            /// <summary>
            ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
            ///     directly from your code. This API may change or be removed in future releases.
            /// </summary>
            [DataType(DataType.Password)]
            [Display(Name = "Confirm password")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { get; set; }

            [Required]
            [Display(Name = "User Role")]
            public string UserRole { get; set; }
        }


        public async Task OnGetAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            var role = _roleManager.FindByIdAsync(Input.UserRole).Result;
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new loginregistrationUser { UserName = Input.Email, Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName };
                 //user = CreateUser();

                await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
                await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var userId = await _userManager.GetUserIdAsync(user);
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return LocalRedirect(returnUrl);
                    }
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ViewData["roles"] = _roleManager.Roles.ToList();

            // If we got this far, something failed, redisplay form
            return Page();
        }

        //private loginregistrationUser CreateUser()
        //{
        //    try
        //    {
        //        return Activator.CreateInstance<loginregistrationUser>();
        //    }
        //    catch
        //    {
        //        throw new InvalidOperationException($"Can't create an instance of '{nameof(loginregistrationUser)}'. " +
        //            $"Ensure that '{nameof(loginregistrationUser)}' is not an abstract class and has a parameterless constructor, or alternatively " +
        //            $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml");
        //    }
        //}

        private IUserEmailStore<loginregistrationUser> GetEmailStore()
        {
            if (!_userManager.SupportsUserEmail)
            {
                throw new NotSupportedException("The default UI requires a user store with email support.");
            }
            return (IUserEmailStore<loginregistrationUser>)_userStore;
        }
    }
}

Register.cshtml.cs:注册.cshtml.cs:

@page
@model RegisterModel
@using login_and_registration.Controllers
@{
    ViewData["Title"] = "Register";
    Layout = "~/Areas/Identity/Pages/_AuthLayout.cshtml";
}

        <form id="registerForm" asp-route-returnUrl="@Model.ReturnUrl" method="post">
           
            <div asp-validation-summary="All" class="text-danger"></div>

            <div class="row">

                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Input.FirstName"></label>
                        <input asp-for="Input.FirstName" class="form-control" autocomplete="username" aria-required="true" />
                        <span asp-validation-for="Input.FirstName" class="text-danger"></span>
                    </div>
                </div>
                 <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Input.LastName"></label>
                        <input asp-for="Input.LastName" class="form-control" autocomplete="username" aria-required="true" />
                        <span asp-validation-for="Input.LastName" class="text-danger"></span>
                    </div>

                </div>
            </div>

            <div class="form-group">
                <label asp-for="Input.Email"></label>
                <input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" />
                <span asp-validation-for="Input.Email" class="text-danger"></span>
            </div>


            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Input.Password"></label>
                        <input asp-for="Input.Password" class="form-control" autocomplete="new-password" aria-required="true" />
                        <span asp-validation-for="Input.Password" class="text-danger"></span>
                    </div>

                </div>
                 <div class="col-md-6">
                    <div class="form-group">
                        <label asp-for="Input.ConfirmPassword"></label>
                        <input asp-for="Input.ConfirmPassword" class="form-control" autocomplete="new-password" aria-required="true" />
                        <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
                    </div>

                </div>

                <div class="col-md-6">

                    <div class="form-group">
                        <label asp-for="Input.UserRole"></label>
                        <select asp-for="Input.UserRole" class="form-control" asp-items='new SelectList(roles,"Id","Name")'>
                        </select>
                        <span asp-validation-for="Input.UserRole" class="text-danger"></span>
                    </div>
                </div>


            </div>


            <button id="registerSubmit" type="submit" class="btn btn-primary">Register</button>

        </form>   

    </div>
        <div class="col-md-6 col-md-offset-2">
        <section>
            <h4>Use another service to register.</h4>
            <hr />
            @{
                if ((Model.ExternalLogins?.Count ?? 0) == 0)
                {
                    <div>
                        <p>
                            There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
                            for details on setting up this ASP.NET application to support logging in via external services.
                        </p>
                    </div>
                }
                else
                {
                    <form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
                        <div>
                            <p>
                                @foreach (var provider in Model.ExternalLogins)
                                {
                                    <button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
                                }
                            </p>
                        </div>
                    </form>
                }
            }
        </section>

    
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

....................................................................................................................................................................... ..................................................... ..................................................... ..................................................... .....................

The problem is the line 61 in you 'Register.cshtml.cs' file and the creation of the SelectList.问题是“Register.cshtml.cs”文件中的第 61 行和 SelectList 的创建。

First, you have reversed the content of the files 'Register.cshtml' and 'Register.cshtml.cs' in you post.首先,您在帖子中颠倒了文件“Register.cshtml”和“Register.cshtml.cs”的内容。 But it's not a problem, just careful.但这不是问题,只要小心。

In the file 'Register.cshtml.cs', instread that:在“Register.cshtml.cs”文件中,说明:

ViewData["roles"] = _roleManager.Roles.ToList();

Do that:去做:

IEnumerable<IdentityRole> roles = _roleManager.Roles.ToList();
ViewData["RoleId"] = new SelectList(roles.ToList(), "Id", "Name");

Again in the 'Register.cshtml.cs', add that in the 'public class InputModel':再次在“Register.cshtml.cs”中,在“public class InputModel”中添加:

[Required]
public string RoleId { get; set; }

Then, is the 'Register.cshtml', instread of that:然后,是“Register.cshtml”,其中包含:

<div class="form-group">
   <label asp-for="Input.UserRole"></label>
      <select asp-for="Input.UserRole" class="form-control" asp-items='new SelectList(roles,"Id","Name")'>
      </select>
      <span asp-validation-for="Input.UserRole" class="text-danger"></span>
</div>

Do that:去做:

<div class="form-group">
   <label asp-for="Input.RoleId" class="control-label"></label>
   <select asp-for="Input.RoleId" class="form-control" asp-items="ViewBag.RoleId"></select>
</div>

It will work perfectly.它将完美地工作。 Tell me if something don't work.告诉我,如果有什么不工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 _Layout.cshtml(16,22):错误CS0103:名称“ HTML”在当前上下文中不存在 - _Layout.cshtml(16,22): error CS0103: The name 'HTML' does not exist in the current context Index.cshtml(7,16):错误CS0103:名称“请求”在当前上下文中不存在 - Index.cshtml(7,16): error CS0103: The name 'Request' does not exist in the current context 错误 CS0103:当前上下文中不存在名称“_context” - Error CS0103: The name '_context' does not exist in the current context 错误 CS0103:当前上下文中不存在名称“currentScreen”(CS0103) - Error CS0103: The name 'currentScreen' does not exist in the current context (CS0103) 错误CS0103:名称“ TimeSpan”在当前上下文(CS0103)(testingProgram)中不存在? - Error CS0103: The name 'TimeSpan' does not exist in the current context (CS0103) (testingProgram)? 错误cs0103名称&#39;IEnumerator&#39;在当前上下文中不存在 - error cs0103 The Name 'IEnumerator' does not exist in the current context 错误CS0103:名称“ HttpUtility”在当前上下文中不存在 - error CS0103: The name `HttpUtility' does not exist in the current context "错误 CS0103:当前上下文中不存在名称“AssetPreview”" - error CS0103: The name 'AssetPreview' does not exist in the current context 错误CS0103:名称“ DebugDisplayString”在当前上下文中不存在 - error CS0103: The name 'DebugDisplayString' does not exist in the current context 错误CS0103:名称“ ressourcesText”在当前上下文中不存在 - error CS0103: The name “ressourcesText” does not exist in the current context
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM