User.Identity.Name/User.Identity.GetUserName 总是 return 电子邮件而不是用户名
User.Identity.Name/User.Identity.GetUserName always return email instead of username
我希望 return 登录部分页面中的用户名而不是电子邮件。我尝试了 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);
}
嗯,我找到了我的问题。我把authticket设置成owner.email,改成owner.Name就可以了。全部。
enter image description here
我希望 return 登录部分页面中的用户名而不是电子邮件。我尝试了 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);
}
嗯,我找到了我的问题。我把authticket设置成owner.email,改成owner.Name就可以了。全部。 enter image description here