首页 > 解决方案 > User.Identity.Name/User.Identity.GetUserName 总是返回电子邮件而不是用户名

问题描述

我希望在登录部分页面而不是电子邮件中返回用户名。我尝试了 viewbag/viewdata/tempdata 并且还声称,但这一切都不起作用。有人可以帮忙吗?数据库 AspNetUsers 用用户名正确保存了用户,而不是电子邮件

风景

@using Microsoft.AspNet.Identity.Owin
@{
    string name = ViewBag.UserName;
}
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        @Html.AntiForgeryToken()

        <ul class="nav navbar-nav navbar-right">
            <li>
                @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
            </li>
            <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
        </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("Register", "RegisterOwner", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
        <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
    </ul>
}

登录视图模型

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

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

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

RegisterViewModel 数据库 AspNetUsers 用用户名而不是电子邮件正确保存了用户,我指定了用户名而不是电子邮件地址。

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

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

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} 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<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            Owner owner = _context.OwnerDB.Where(o => o.email.ToLower() == model.Email.ToLower() && o.password == model.Password).FirstOrDefault();
            if (owner!=null)
            {
                FormsAuthentication.SetAuthCookie(model.Email, false);
                var authTicket = new FormsAuthenticationTicket(1, owner.email, DateTime.Now, DateTime.Now.AddMinutes(20), false, "owner");
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                HttpContext.Response.Cookies.Add(authCookie);
               
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
            }
            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        TempData["User"] = model.Email;
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
        }


 [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> RegisterOwner(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {

                var user = new ApplicationUser { UserName = model.Username, Email = model.Email };
                var owner = new Owner();
                owner.Name = model.Username;
                owner.joinDate = DateTime.Now.ToString("yyyy-MMM-dd");
                owner.email = model.Email;
                owner.password = model.Password;
                _context.OwnerDB.Add(owner);
                _context.SaveChanges();
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    var authTicket = new FormsAuthenticationTicket(1, owner.email, DateTime.Now, DateTime.Now.AddMinutes(20), false, "owner");
                    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                    var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                    HttpContext.Response.Cookies.Add(authCookie);

                    //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                    //TempData["User"] = user.UserName;
                   // ViewData["UserName"] = owner.Name;
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

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

标签: asp.netasp.net-mvcauthenticationmodel-view-controlleruser-controls

解决方案


嗯,我发现了我的问题。我将 authticket 设置为 owner.email,只需更改为 owner.Name 即可。全部。 在此处输入图像描述


推荐阅读