如何解决ASP.NET MVC-重新配置登录注销,以便在用户登录或注销时可以在导航栏中进行更改
我已经创建了一个标准的ASP NET MVC模板应用程序,现在我已经在一页中插入了评论和回复。为此,我必须更改与VS模板一起使用的“注册和登录”标准方法,因为我还创建了一个数据库来存储凭据。
这是以前的样子,也是我试图实现的目标:
这是NAvBar现在的外观,即使我已经登录,它也没有改变,图片上的单词是“ login”和“ register”:
在登录之前,导航栏在右上角更改为“ Hello用户”,然后注销。 现在,尽管我使用新方法登录,但我可以发布评论(如果未登录,则无法执行),导航栏保持不变。 (即使我已经登录,在右上角仍然有“注册并登录”选项。) 以下是在标准ASP NET MVC模板中登录的初始方法
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(Loginviewmodel model,string returnUrl)
{
if (!ModelState.IsValid)
{
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:
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);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(Registerviewmodel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email,Email = model.Email };
var result = await UserManager.CreateAsync(user,model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user,isPersistent: false,rememberbrowser: false);
// For more information on how to enable account confirmation and password reset please visit http://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>");
return RedirectToAction("Index","Home");
}
AddErrors(result);
}
// If we got this far,something Failed,redisplay form
return View(model);
}
private ApplicationDBContext db = new ApplicationDBContext();
//GET: Account/RegisterTurist (new)
[HttpGet]
[AllowAnonymous]
public ActionResult RegisterTurist()
{
return View();
}
// POST: /Account/RegisterTurist (new)
[HttpPost]
[AllowAnonymous]
public ActionResult RegisterTurist(RegisterVM obj)
{
bool UserExists = db.Users.Any(x => x.Username == obj.Username);
if (UserExists) //if the username is already in the database and exists
{
ViewBag.UsernameMessage = " This username is already in use,please try another";
return View();
}
bool EmailExists = db.Users.Any(x => x.Email == obj.Email);
if (EmailExists) // if the email is already in the database and it exists
{
ViewBag.EmailMessage = " This Email is already in use,please try another";
return View();
}
// if Username and Email are unique we register the user and save it in the database
User u = new User();
u.Username = obj.Username;
u.Password = obj.Password;
u.Email = obj.Email;
u.ImageUrl = " ";
u.CreatedOn = DateTime.Now;
db.Users.Add(u);
db.SaveChanges();
return RedirectToAction("Experiences","Home");
}
//GET: Account/LoginTurist (new)
[HttpGet]
[AllowAnonymous]
public ActionResult LoginTurist()
{
return View();
}
//POST: Account/LoginTurist (new)
[HttpPost]
[AllowAnonymous]
public ActionResult LoginTurist(LoginVM obj)
{
bool userExists = db.Users.Any(u => u.Username == obj.Username && u.Password == obj.Password);
if(userExists)
{
Session["UseId"]=db.Users.Single(x=> x.Username == obj.Username).Id;
return RedirectToAction ("Experiences","Home");
}
// in case of incorect email or password
ViewBag.LoginMessage = "Nume utilizator sau parola incorecte!";
return View();
}
我研究了一下,弄清楚了该应用程序如何确定用户是否登录,因此它切换了导航栏。 它发生在应用程序的LoginPArtial中:
@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("logoff",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("Inregistrare","Register",htmlAttributes: new { id = "registerLink" })</li>*@
@*<li>@Html.ActionLink("Autentificare","Login",htmlAttributes: new { id = "loginLink" })</li>*@
<li>@Html.ActionLink("Inregistrare","RegisterTurist",htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Autentificare","LoginTurist",htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
在 AccountController.cs 中,我可以帮助您检查用户是否已登录。
//POST: Account/LoginTurist (new)
[HttpPost]
[AllowAnonymous]
public ActionResult LoginTurist(LoginVM obj)
{
bool userExists = db.Users.Any(u => u.Username == obj.Username && u.Password == obj.Password);
//bool userLoggedIn = false;
if(userExists)
{
Session["UseId"]=db.Users.Single(x=> x.Username == obj.Username).Id;
//userLoggedIn = true;
return RedirectToAction ("Experiences","Home");
}
// in case of incorect email or password
ViewBag.LoginMessage = "Nume utilizator sau parola incorecte!";
return View();
}
如何在该 if语句的 LoginPArtial.chtml 中使用 Session [“ UseID”] ? 还是我尝试过的 userLoggedIn 这样的布尔符号,用这种方法是更好还是更容易?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。