asp.net mvc 实现登录的控制器代码
时间: 2023-04-04 15:03:09 浏览: 113
以下是一个简单的 ASP.NET MVC 登录控制器代码示例:
```
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "用户名或密码不正确。");
}
}
return View(model);
}
```
该代码使用 ASP.NET Membership API 验证用户凭据,并在验证成功后设置身份验证 cookie。如果验证失败,则将错误消息添加到模型状态中以供显示。
相关问题
asp.net mvc 实现登录的控制器,视图代码
以下是一个简单的 ASP.NET MVC 登录控制器和视图代码示例:
控制器代码:
```
public class AccountController : Controller
{
// GET: Account/Login
public ActionResult Login()
{
return View();
}
// POST: Account/Login
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
// 验证用户输入的用户名和密码是否正确
if (model.Username == "admin" && model.Password == "password")
{
// 登录成功,将用户信息存储在 Session 中
Session["Username"] = model.Username;
return RedirectToAction("Index", "Home");
}
else
{
// 登录失败,添加错误信息到 ModelState 中
ModelState.AddModelError("", "用户名或密码不正确");
}
}
// 如果代码执行到这里,说明登录失败,返回登录视图并显示错误信息
return View(model);
}
// GET: Account/Logout
public ActionResult Logout()
{
// 清除 Session 中的用户信息
Session.Clear();
return RedirectToAction("Index", "Home");
}
}
```
视图代码:
```
@model LoginViewModel
@{
ViewBag.Title = "登录";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(m => m.Username)
@Html.TextBoxFor(m => m.Username, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Username)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password)
</div>
<button type="submit" class="btn btn-primary">登录</button>
}
```
注意:以上代码仅供参考,实际应用中需要根据具体需求进行修改和完善。
asp.net mvc实现注册登录详细代码
以下是ASP.NET MVC实现注册和登录的详细代码:
首先是注册页面的视图代码(Register.cshtml):
```
@model YourNamespace.ViewModels.RegisterViewModel
@{
ViewBag.Title = "Register";
}
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<hr />
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.ConfirmPassword)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
```
接下来是注册页面的模型代码(RegisterViewModel.cs):
```
using System.ComponentModel.DataAnnotations;
namespace YourNamespace.ViewModels
{
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { 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; }
}
}
```
然后是注册页面的控制器代码(AccountController.cs):
```
using System.Threading.Tasks;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using YourNamespace.Models;
using YourNamespace.ViewModels;
namespace YourNamespace.Controllers
{
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public AccountController()
{
_userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
}
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
[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 SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
}
private IAuthenticationManager AuthenticationManager => HttpContext.GetOwinContext().Authentication;
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
}
```
现在是登录页面的视图代码(Login.cshtml):
```
@model YourNamespace.ViewModels.LoginViewModel
@{
ViewBag.Title = "Log in";
}
<h2>@ViewBag.Title.</h2>
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<hr />
<div class="form-group">
@Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Email)
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
<label>
@Html.CheckBoxFor(m => m.RememberMe) Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-default">Log in</button>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
```
然后是登录页面的模型代码(LoginViewModel.cs):
```
using System.ComponentModel.DataAnnotations;
namespace YourNamespace.ViewModels
{
public class LoginViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
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; }
}
}
```
最后是登录页面的控制器代码(AccountController.cs):
```
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using YourNamespace.Models;
using YourNamespace.ViewModels;
namespace YourNamespace.Controllers
{
public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
public AccountController()
{
_userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
}
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
[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 SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
[HttpGet]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await _userManager.FindAsync(model.Email, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
ModelState.AddModelError("", "Invalid username or password.");
}
return View(model);
}
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
}
private IAuthenticationManager AuthenticationManager => HttpContext.GetOwinContext().Authentication;
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
}
}
```
这些代码提供了一个基本的注册和登录系统,但您可以根据自己的需求进行修改和扩展。