在本节中,我将说明将ASP.NET Identity添加到现有的项目或者一个空项目。我将介绍你需要添加的Nuget和Class。此示例中,会使用LocalDB。

本节目录:

注册用户

注册用户涉及到的EF和Identity.Core 2个程序集。

新建项目

新建1个MVC项目或者一个空的WebForm项目都可以,在这里我使用MVC5(with no authentication)。

添加Nuget

包名:Microsoft.AspNet.Identity.EntityFramework

(它会同时引用EntityFrameworkMicrosoft.AspNet.Identity.Core2个包)

新建控制器

新建一个Account控制器用来管理用户登入登出注册等用户管理功能。

  1. using System.Linq;
  2. using EmptyMVC.Models.Account;
  3. using System.Web.Mvc;
  4. using Microsoft.AspNet.Identity;
  5. using Microsoft.AspNet.Identity.EntityFramework;
  6.  
  7. namespace EmptyMVC.Controllers
  8. {
  9. public class AccountController : Controller
  10. {
  11. //
  12. // GET: /Account/
  13. public ActionResult Register()
  14. {
  15. return View();
  16. }
  17.  
  18. [HttpPost]
  19. [ValidateAntiForgeryToken]
  20. public ActionResult Register(RegisterModel model)
  21. {
  22. if (ModelState.IsValid)
  23. {
  24. // UserStore 默认构造函数会使用默认连接字符串: DefaultConnection
  25. var userStore = new UserStore<IdentityUser>();
  26. var manager = new UserManager<IdentityUser>(userStore);
  27. var user = new IdentityUser() { UserName = model.Name };
  28. var result = manager.Create(user, model.Pwd);
  29. if (result.Succeeded)
  30. {
  31. return Content(user.UserName + "创建成功,id:" + user.Id);
  32. }
  33. var erro = result.Errors.FirstOrDefault();
  34. ModelState.AddModelError("",erro);
  35. }
  36. return View(model);
  37. }
  38. }
  39. }

在这里需要引入一个ViewModel

  1. using System.ComponentModel.DataAnnotations;
  2.  
  3. namespace EmptyMVC.Models.Account
  4. {
  5. public class RegisterModel
  6. {
  7. [Required]
  8. [Display(Name = "用户名")]
  9. public string Name { get; set; }
  10.  
  11. [Required]
  12. [StringLength(, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = )]
  13. [DataType(DataType.Password)]
  14. [Display(Name = "密码")]
  15. public string Pwd { get; set; }
  16.  
  17. [DataType(DataType.Password)]
  18. [Display(Name = "确认密码")]
  19. [Compare("Pwd", ErrorMessage = "密码和确认密码不匹配。")]
  20. public string ConfirmPwd { get; set; }
  21. }
  22. }

连接字符串

  1. <connectionStrings>
  2. <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\MVCIdentity.mdf;Initial Catalog=MVCIdentity;Integrated Security=True"
  3. providerName="System.Data.SqlClient" />
  4. </connectionStrings>

创建视图

可以通过MVC自动生成。本质是一个创建页面。

以下是通过生成后的razor视图稍微修改2处显示字符串而成

  1. @model EmptyMVC.Models.Account.RegisterModel
  2.  
  3. @{
  4. ViewBag.Title = "Register";
  5. }
  6.  
  7. <h2>Register</h2>
  8.  
  9. @using (Html.BeginForm())
  10. {
  11. @Html.AntiForgeryToken()
  12.  
  13. <div class="form-horizontal">
  14. <h4>RegisterModel</h4>
  15. <hr />
  16. @Html.ValidationSummary(true)
  17.  
  18. <div class="form-group">
  19. @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
  20. <div class="col-md-10">
  21. @Html.EditorFor(model => model.Name)
  22. @Html.ValidationMessageFor(model => model.Name)
  23. </div>
  24. </div>
  25.  
  26. <div class="form-group">
  27. @Html.LabelFor(model => model.Pwd, new { @class = "control-label col-md-2" })
  28. <div class="col-md-10">
  29. @Html.EditorFor(model => model.Pwd)
  30. @Html.ValidationMessageFor(model => model.Pwd)
  31. </div>
  32. </div>
  33.  
  34. <div class="form-group">
  35. @Html.LabelFor(model => model.ConfirmPwd, new { @class = "control-label col-md-2" })
  36. <div class="col-md-10">
  37. @Html.EditorFor(model => model.ConfirmPwd)
  38. @Html.ValidationMessageFor(model => model.ConfirmPwd)
  39. </div>
  40. </div>
  41.  
  42. <div class="form-group">
  43. <div class="col-md-offset-2 col-md-10">
  44. <input type="submit" value="注册" class="btn btn-default" />
  45. </div>
  46. </div>
  47. </div>
  48. }
  49.  
  50. <div>
  51. @Html.ActionLink("回到首页", "Index")
  52. </div>
  53.  
  54. @section Scripts {
  55. @Scripts.Render("~/bundles/jqueryval")
  56. }

注意:这里最后通过scripts节点在模板页中插入绑定的jqueryval,是用来在客户端验证Model的,一般需要在Nuget下引用Validate包后,在BundleConfig下需要再绑定一下才可以使用。

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*"));

开始注册

填写注册信息

注册成功!

在数据库里:

登入登出

现在,我将展示如何登入用户,ASP.NET Identity使用OWIN作为身份验证。

Nuget搜索下载

a.Identity.Owin(OWIN核心)

b.Microsoft.Owin.Host.SystemWeb(for OWIN app run on iis)

添加OWIN Startup文件

配置(添加红色区域)

  1. using Microsoft.AspNet.Identity;
  2. using Microsoft.Owin;
  3. using Microsoft.Owin.Security.Cookies;
  4. using Owin;
  5.  
  6. [assembly: OwinStartup(typeof(EmptyMVC.Startup))]
  7.  
  8. namespace EmptyMVC
  9. {
  10. public class Startup
  11. {
  12. public void Configuration(IAppBuilder app)
  13. {
  14. // 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
  15. app.UseCookieAuthentication(new CookieAuthenticationOptions
  16. {
  17. AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
  18. LoginPath = new PathString("/Account/Login")
  19. });
  20. }
  21. }
  22. }

添加登入登出方法

  1. using System.Linq;
  2. using System.Web;
  3. using EmptyMVC.Models.Account;
  4. using System.Web.Mvc;
  5. using Microsoft.AspNet.Identity;
  6. using Microsoft.AspNet.Identity.EntityFramework;
  7. using Microsoft.Owin.Security;
  8.  
  9. namespace EmptyMVC.Controllers
  10. {
  11. public class AccountController : Controller
  12. {
  13. public ActionResult Index()
  14. {
  15. return View(User);
  16. }
  17.  
  18. public ActionResult LogOff()
  19. {
  20. var authenticationManager = HttpContext.GetOwinContext().Authentication;
  21. authenticationManager.SignOut();
  22. return Redirect("Login");
  23. }
  24.  
  25. public ActionResult Login()
  26. {
  27. return View();
  28. }
  29.  
  30. [HttpPost]
  31. [ValidateAntiForgeryToken]
  32. public ActionResult Login(LoginModel model)
  33. {
  34. if (ModelState.IsValid)
  35. {
  36. var userStore = new UserStore<IdentityUser>();
  37. var userManager = new UserManager<IdentityUser>(userStore);
  38. var user = userManager.Find(model.Name, model.Pwd);
  39. if (user != null)
  40. {
  41. var authenticationManager = HttpContext.GetOwinContext().Authentication;
  42. var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
  43. authenticationManager.SignIn(userIdentity);
  44. return LoginRedirect();
  45. }
  46. }
  47. return View(model);
  48. }
  49.  
  50. //
  51. // GET: /Account/
  52. public ActionResult Register()
  53. {
  54. return View();
  55. }
  56.  
  57. [HttpPost]
  58. [ValidateAntiForgeryToken]
  59. public ActionResult Register(RegisterModel model)
  60. {
  61. if (ModelState.IsValid)
  62. {
  63. // UserStore 默认构造函数会使用默认连接字符串: DefaultConnection
  64. var userStore = new UserStore<IdentityUser>();
  65. var manager = new UserManager<IdentityUser>(userStore);
  66. var user = new IdentityUser() { UserName = model.Name };
  67. var result = manager.Create(user, model.Pwd);
  68. if (result.Succeeded)
  69. {
  70. var authenticationManager = HttpContext.GetOwinContext().Authentication;
  71. var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
  72. authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
  73. return LoginRedirect();
  74. }
  75. var erro = result.Errors.FirstOrDefault();
  76. ModelState.AddModelError("", erro);
  77. }
  78. return View(model);
  79. }
  80.  
  81. private ActionResult LoginRedirect()
  82. {
  83. var url = HttpContext.Request["returnurl"];
  84. if (string.IsNullOrEmpty(url))
  85. return Redirect(Url.Action("Index"));
  86. return Redirect(url);
  87. }
  88. }
  89. }

AccountController

这里需要一个LoginModel

  1. public class LoginModel
  2. {
  3. [Required]
  4. [Display(Name = "用户名")]
  5. public string Name { get; set; }
  6.  
  7. [Required]
  8. [StringLength(, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = )]
  9. [DataType(DataType.Password)]
  10. [Display(Name = "密码")]
  11. public string Pwd { get; set; }
  12. }

添加View

Login

  1. @model EmptyMVC.Models.Account.LoginModel
  2.  
  3. @{
  4. ViewBag.Title = "Login";
  5. }
  6.  
  7. <h2>Login</h2>
  8.  
  9. @using (Html.BeginForm())
  10. {
  11. @Html.AntiForgeryToken()
  12.  
  13. <div class="form-horizontal">
  14. <h4>LoginModel</h4>
  15. <hr />
  16. @Html.ValidationSummary(true)
  17.  
  18. <div class="form-group">
  19. @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
  20. <div class="col-md-10">
  21. @Html.EditorFor(model => model.Name)
  22. @Html.ValidationMessageFor(model => model.Name)
  23. </div>
  24. </div>
  25.  
  26. <div class="form-group">
  27. @Html.LabelFor(model => model.Pwd, new { @class = "control-label col-md-2" })
  28. <div class="col-md-10">
  29. @Html.EditorFor(model => model.Pwd)
  30. @Html.ValidationMessageFor(model => model.Pwd)
  31. </div>
  32. </div>
  33.  
  34. <div class="form-group">
  35. <div class="col-md-offset-2 col-md-10">
  36. <input type="submit" value="登录" class="btn btn-default" />
  37. </div>
  38. </div>
  39. </div>
  40. }
  41.  
  42. <div>
  43. @Html.ActionLink("回到首页", "Index")
  44. </div>
  45.  
  46. @section Scripts {
  47. @Scripts.Render("~/bundles/jqueryval")
  48. }

Index

  1. @using Microsoft.AspNet.Identity
  2. @model System.Security.Principal.IPrincipal
  3. @{
  4. ViewBag.Title = "Index";
  5. }
  6.  
  7. <h2>Index</h2>
  8. @if (Model.Identity.IsAuthenticated)
  9. {
  10. <h3>Hello @Model.Identity.GetUserName() !</h3>
  11. using (Html.BeginForm("LogOff","Account"))
  12. {
  13. Html.AntiForgeryToken();
  14. <input type="submit" value="退出"/>
  15. }
  16. }
  17. else
  18. {
  19. <ul class="nav navbar-nav navbar-right">
  20. <li>@Html.ActionLink("注册", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
  21. <li>@Html.ActionLink("登录", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
  22. </ul>
  23. }

开始登录

填写登录信息,点击登录

登录成功(点击退出,即可登出用户)

本文作者:Never、C

本文链接:http://www.cnblogs.com/neverc/p/4730439.html

[Solution] ASP.NET Identity(2) 空的项目使用的更多相关文章

  1. [Solution] ASP.NET Identity(1) 快速入门

    本节将介绍: ASP.NET Identity简介 快速入门 扩展 ASP.NET Identity简介 身份管理在ASP.NET中存在很长世间了,ASP.NET 开发团队已经学会了很多从客户的反馈. ...

  2. 【ASP.NET Identity系列教程(一)】ASP.NET Identity入门

    注:本文是[ASP.NET Identity系列教程]的第一篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序 ...

  3. ASP.NET Identity 一 (转载)

    来源:http://www.cnblogs.com/r01cn/p/5194257.html 注:本文是[ASP.NET Identity系列教程]的第一篇.本系列教程详细.完整.深入地介绍了微软的A ...

  4. ASP.NET Identity系列教程-2【Identity入门】

    https://www.cnblogs.com/r01cn/p/5177708.html13 Identity入门 Identity is a new API from Microsoft to ma ...

  5. MVC使用ASP.NET Identity 2.0实现用户身份安全相关功能,比如通过短信或邮件发送安全码,账户锁定等

    本文体验在MVC中使用ASP.NET Identity 2.0,体验与用户身份安全有关的功能: →install-package Microsoft.AspNet.Identity.Samples - ...

  6. 向空项目添加 ASP.NET Identity

    安装 AspNet.Identity 程序包 Microsoft.AspNet.Identity.Core 包含 ASP.NET Identity 核心接口Microsoft.AspNet.Ident ...

  7. VS2013中web项目中自动生成的ASP.NET Identity代码思考

    vs2013没有再分webform.mvc.api项目,使用vs2013创建一个web项目模板选MVC,身份验证选个人用户账户.项目会生成ASP.NET Identity的一些代码.这些代码主要在Ac ...

  8. ASP.NET Identity 2集成到MVC5项目--笔记01

    Identiry2是微软推出的Identity的升级版本,较之上一个版本更加易于扩展,总之更好用.如果需要具体细节.网上具体参考Identity2源代码下载 参考文章 在项目中,是不太想直接把这一堆堆 ...

  9. ASP.NET Identity 2集成到MVC5项目--笔记02

    ASP.NET Identity 2集成到MVC5项目--笔记01 ASP.NET Identity 2集成到MVC5项目--笔记02 继上一篇,本篇主要是实现邮件.用户名登陆和登陆前邮件认证. 1. ...

随机推荐

  1. Scala 深入浅出实战经典 第53讲:Scala中结构类型实战详解

    王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-64讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...

  2. android studio clone 失败

    Clone failedunable to access 'https://git.oschina.net/xx/xx.git/': Failed to connect to x.tu26.net p ...

  3. [CoreOS 转载] CoreOS实践指南(五):分布式数据存储Etcd(上)

    转载:http://www.csdn.net/article/2015-01-22/2823659 摘要:在“漫步云端:CoreOS实践指南”系列的前几篇,分别介绍了如何架设CoreOS集群,系统服务 ...

  4. iOS客户端的在线安装和更新——针对ADHoc证书

    这篇文章纯给自己留个备份,所以对AdHoc证书内部分发和对iOS客户端开发不了解的请直接无视. 一般在iOS游戏或应用开发过程中,正式发布到App Store之前,都需要内部的测试,客户端的安装是个不 ...

  5. sudo 使用不了, the permissions on the /etc/sudoers file are changed to something other than 0440

    sudo 使用不了,报错: the permissions on the /etc/sudoers file are changed to something other than 0440 how ...

  6. js 事件捕获与事件冒泡例子

    http://codepen.io/huashiyiqike/pen/qZVdag addEventListener 默认是冒泡阶段执行,也就是父亲与子都监听时,点击子,子先处理,父亲再处理,这时加s ...

  7. Android下海康实时视频解码

    折腾了一个多月,终于调出来了.....首先吐槽一下海康SDK,同时也感谢之... 手头有个项目,需要实时抓取海康摄像头,我是在Android下实现的,海康官网上没有Android SDK,这里友情提醒 ...

  8. sublime3+wamp配置php,(无需配环境变量)

    思来想去,最后还是决定给自己的手游加简单后端验证.好久没搞php了,最近搜了搜资料,发现现在php比几年前方便简单的多,有wampserver和sublime用.想想当年我还用记事本+phnow呢. ...

  9. IOS 使用SDWebImage实现仿新浪微博照片浏览器

    使用第三方库SDWebImage实现仿新浪微博照片浏览器,可以下载图片缓存,点击之后滚动查看相片,具体效果如下: 代码如下: WeiboImageView.h: #import <UIKit/U ...

  10. BZOJ 1251 序列终结者(Splay)

    题目大意 网上有许多题,就是给定一个序列,要你支持几种操作:A.B.C.D.一看另一道题,又是一个序列要支持几种操作:D.C.B.A.尤其是我们这里的某人,出模拟试题,居然还出了一道这样的,真是没技术 ...