ASP.NET核心:如何使用“用户名”而不是“电子邮件”登录?

kupeojn6  于 2023-06-25  发布在  .NET
关注(0)|答案(4)|浏览(106)

使用asp.net核心,所有登录页面和视图模型等都隐藏在引用的包中,因此不能直接更改。我如何允许登录仍然使用用户名,而不是强制使用电子邮件?

9udxz4iz

9udxz4iz1#

第一步是将身份搭建到应用程序中:
Scaffold Identity in ASP.NET Core projects
然后,您可以自定义Register.cshtml/Register.cshtml.csLogin.cshtml/Login.cshtml.cs,更新模型和视图,并更改OnPostAsync函数中的逻辑以满足您的需求。
根据您的要求,您可以按照以下步骤操作:
1.脚手架身份到您的项目。
1.修改Register.cshtml.cs,将Username添加到InputModel

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

1.修改OnPostAsync方法:

var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };

1.更新Register.cshtml以包含用户名:

<div class="form-group">
    <label asp-for="Input.UserName"></label>
    <input asp-for="Input.UserName" class="form-control"/>
    <span asp-validation-for="Input.UserName" class="text-danger"></span>
</div>

1.修改Login.cshtml.cs,修改InputModel以将Email替换为用户名:

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

1.修改Login.cshtml

<div class="form-group">
    <label asp-for="Input.UserName"></label>
    <input asp-for="Input.UserName" class="form-control" />
    <span asp-validation-for="Input.UserName" class="text-danger"></span>
</div>

1.修改Login.cshtml.csOnPostAsync方法以使用Username而不是email:

var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);

默认情况下,ASP.NET Identity使用FindByNameAsync来检查是否存在具有给定名称的用户,这样您就不需要在SignInManager中重写PasswordSignInAsync函数。如果您想通过电子邮件登录,您可以点击这里更新。

rseugnpd

rseugnpd2#

在使用excepted answer时,我还必须在最新的ASP.NET Core模板上将第三步中的以下行从Input.Email修改为Input.UserName

await _userStore.SetUserNameAsync(user, Input.UserName, CancellationToken.None);
zaqlnxep

zaqlnxep3#

查看Pages-> Login.cshtml页面(在这里,您将得到一个名为Login.cshtml.cs的类)。在该类中,您将获得一个名为'OnPostAsync'的方法
按喜好更改前端

在'Login.cshtml.cs'类中,使用目标Dashboard/Index url更改此方法。

public async Task<IActionResult> OnPostAsync()
    {
        if (ModelState.IsValid)
        {
            var validated = _ADService.Validate(new NetworkCredential(LoginData.UserId, LoginData.Password));
            if (validated)
            {
                if (await _identityService.SignInAsync(HttpContext, LoginData.UserId))
                {

              //   return Redirect("Index");
                   return Redirect("../app/bootstrap.html");

                }

                ModelState.AddModelError("", "account does not exist in system!");
                return Page();
            }

            ModelState.AddModelError("", "userid or password is invalid!");
            return Page();
        }
        else
        {
            ModelState.AddModelError("", "userid or password is blank!");
            return Page();
        }
    }
lb3vh1jj

lb3vh1jj4#

请考虑:当使用例外答案时,如果你不想让你的用户点击愚蠢的“确认电子邮件”按钮,你需要:
1.将Program.cs中的AddDefaultIdentity函数更改为options.SignIn.RequireConfirmedAccount = false(非默认true)。
1.删除Register.cshtml.cs中与电子邮件确认相关的所有内容
有完整的,清晰的和工作的Register.cshtml.cs没有任何愚蠢的电子邮件的东西。

#nullable disable

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;

namespace PhotoSite.Areas.Identity.Pages.Account
{
    public class RegisterModel : PageModel
    {
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly UserManager<IdentityUser> _userManager;
        private readonly IUserStore<IdentityUser> _userStore;
        private readonly ILogger<RegisterModel> _logger;

        public RegisterModel(
            UserManager<IdentityUser> userManager,
            IUserStore<IdentityUser> userStore,
            SignInManager<IdentityUser> signInManager,
            ILogger<RegisterModel> logger)
        {
            _userManager = userManager;
            _userStore = userStore;
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public string ReturnUrl { get; set; }

        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        public class InputModel
        {
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "User Name")]
            public string UserName { get; set; }

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

            [DataType(DataType.Password)]
            [Display(Name = "Confirm password")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { 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("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = CreateUser();

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

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(returnUrl);
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            // If we got this far, something failed, redisplay form
            return Page();
        }

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

相关问题