Search code examples
asp.net-mvcasp.net-coreasp.net-identity

ASP.NET Identity Register new user to use UserName as UserName not Email, but still not displaying who is logged in


Trying to set UserName while Registering a new user from Input.UserName and not use Input.Email. After much research the most thorough post though a bit outdated was here

I am using: Microsoft Visual Studio Community 2019 Version 16.5.3; ASP.NET Web Frameworks and Tools 2019 16.5.236.49856; ASPNETCore 3.1.3

Of course most of the Identity items are not exposed, but following this post over half way down you can see how to expose the Register view and class (which now displays in the Areas section of the project and not Views)

Added to the Register.cshtml InputModel class file so that it is then available to the Register.cshtml.cs

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

In the Register.cshtml file added:

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

Set <IdentityOptions> requirements in Startup.cs services.Configure<IdentityOptions>(options => from this post

Lastly in the Register.cshtml I changed it from/to:

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

I run the program and register a new user. It is entered into the DB but the page does not refresh showing the UserName of who is logged in. In the _LayoutPartial.cshtml in the View/Shared I have the

    @using Microsoft.AspNetCore.Identity
    @inject SignInManager<IdentityUser> SignInManager
    @inject UserManager<IdentityUser> UserManager

    <ul class="navbar-nav">
    @if (SignInManager.IsSignedIn(User))
    { 
        <li class="nav-item">
            <a  class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</a>

the User is empty and so never enters this code; but also the @User.Identity.UserName is not available.


Solution

  • The _LoginPartial.cshtml looks to the file Login.cshtml.cs where the SignInManager's method PasswordSignInAsync is called but there are two and the default is to pass in UserName to validate user; which you don't have if you are logging in with email and password, as UserName does not equal Email anymore. So my below code uses the other PasswordSignInAsync that uses a <TUser> to use for validation.

    var result = await _signInManager.PasswordSignInAsync(_userManager.FindByEmailAsync(Input.Email).Result, Input.Password, Input.RememberMe, lockoutOnFailure: false);