博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Asp.Net MVC 5使用Identity之简单的注册和登陆
阅读量:4608 次
发布时间:2019-06-09

本文共 7843 字,大约阅读时间需要 26 分钟。

由于.Net MVC 5登陆和注册方式有很多种,但是Identity方式去实现或许会更简单更容易理解

首先新建一个项目

 

其次如下选择Empty和MVC的选项

然后打开NuGet包管理器分别安装几个包

  1. EntityFramework
  2. Microsoft.AspNet.Identity.Core
  3. Microsoft.AspNet.Identity.EntityFramework
  4. Microsoft.AspNet.Identity.Owin
  5. Modernizr
  6. Microsoft.Owin.Host.SystemWeb
  7. Bootstrap

然后往Models文件夹里面添加ApplicationUser类,SignInModel类,SignUpModel类,ApplicationDbContext类,当然ApplicationDbContext类你也可以分到DbContext到另一个类库,我这是做演示用的,分层不用么这么明确

----------------------------------------------------------------------

ApplicationUser类

ApplicationDbContext类

SignInModel类

SignUpModel

然后往App_Start文件夹里面添加ApplicationSignInManager类,ApplicationUserManager类,ApplicationUserStore类

---------------------------------------------------------------------

ApplicationUserManager类

ApplicationSignInManager类

ApplicationUserStore类

 

然后往Controller文件夹里面添加HomeController控制器,AccountController控制器

先往HomeController控制器里添加index视图

index视图代码

@using Microsoft.AspNet.Identity@{    ViewBag.Title = "Index";}

Index

@if (Request.IsAuthenticated){ using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken()

Hello @User.Identity.GetUserName()

}}else{
  • @Html.ActionLink("Login", "Login", "Account")
  • @Html.ActionLink("Register", "Register", "Account")
}

然后AccountController控制器代码

private ApplicationSignInManager signInManager;        private ApplicationUserManager userManager;        public ApplicationSignInManager SignInManager        {            get            {                return signInManager ?? HttpContext.GetOwinContext().Get
(); } private set { signInManager = value; } } public ApplicationUserManager UserManager { get { return userManager ?? HttpContext.GetOwinContext().GetUserManager
(); } private set { userManager = value; } } [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task
Login(SignInModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.Failure: default: ModelState.AddModelError("", "登陆无效"); return View(model); } } [AllowAnonymous] public ActionResult Register() { return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task
Register(SignUpModel 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); return RedirectToAction("Index", "Home"); } AddErrors(result); } return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { AuthenticationManager.SignOut(); return RedirectToAction("Index", "Home"); } 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"); } private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }

然后分别添加生成Login和Register页面

Login页面代码

@model IdentityDemo.Models.SignInModel@{    ViewBag.Title = "Login";}

Login

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post)){ @Html.AntiForgeryToken()

SignInModel


@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.RememberMe, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.CheckBoxFor(model => model.RememberMe) @Html.ValidationMessageFor(model => model.RememberMe, "", new { @class = "text-danger" })
}
@Html.ActionLink("注册", "Register")

Register页面代码

@model IdentityDemo.Models.SignUpModel@{    ViewBag.Title = "Register";}

Register

@using (Html.BeginForm("Register", "Account", FormMethod.Post)){ @Html.AntiForgeryToken()

SignUpModel


@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.PasswordFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
}

然后往项目的根目录添加Startup类

然后修改根目录的Web.Config文件

最后我们来测试一下看看效果怎么样,如下图

转载于:https://www.cnblogs.com/R00R/p/7487655.html

你可能感兴趣的文章
JS秒数转成分秒时间格式
查看>>
xp_cmdshell 命令的开启与关闭,和状态查询
查看>>
Linux sudoers
查看>>
MySQL详解(18)-----------分页方法总结
查看>>
bzoj 4595 激光发生器
查看>>
multi cookie & read bug
查看>>
js时间转换
查看>>
(转载) Android Studio你不知道的调试技巧
查看>>
POJ2231 Moo Volume 递推 C语言
查看>>
struts2类型转换的具体流程
查看>>
Hdu 1203 I NEED A OFFER!
查看>>
php文件上传类
查看>>
CF219D Choosing Capital for Treeland
查看>>
luogu P3809 【模板】后缀排序
查看>>
Matlab画图-非常具体,非常全面
查看>>
365. Water and Jug Problem
查看>>
队列实现霍夫曼树
查看>>
【Java】图片高质量缩放类
查看>>
详解定位与定位应用
查看>>
【前端开发】 5分钟创建 Mock Server
查看>>