注册\区域\标识\页面\帐户\注册.cshtml(61,78,61,83):错误 CS0103:当前上下文中不存在名称'roles'



我正在尝试使用Identity构建一个带有角色的注册系统,以查看我的Asp.Net核心项目中有限制的数据,所以我遇到了这个错误,如果有人指导我找到解决方案,我将不胜感激。。。。。。。。。。。。。。。。。。。。。。。。。。。。

and registrationAreasIdentityPagesAccountRegister.cshtml(61,78,61,83): error CS0103: The name 'roles' does not exist in the current context

程序.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();

角色控制器:

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:

// 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:

@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" />
}

问题是"Register.cshtml.cs"文件中的第61行和SelectList的创建。

首先,您颠倒了您发布的文件"Register.cshtml"one_answers"Register.cs.html.cs"的内容。但这不是问题,只是要小心。

在文件"Register.cs.html.cs"中,instread that:

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

这样做:

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

再次在"Register.cs.html.cs"中,将其添加到"public class InputModel"中:

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

然后,是"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>

这样做:

<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>

它将完美工作!如果有什么不起作用,就告诉我。

相关内容

最新更新