Asp.Net MVC 5使用Identity之简单的注册和登陆
由于.Net MVC 5登陆和注册方式有很多种,但是Identity方式去实现或许会更简单更容易理解
首先新建一个项目

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

然后打开NuGet包管理器分别安装几个包
- EntityFramework
- Microsoft.AspNet.Identity.Core
- Microsoft.AspNet.Identity.EntityFramework
- Microsoft.AspNet.Identity.Owin
- Modernizr
- Microsoft.Owin.Host.SystemWeb
- 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";
} <h2>Index</h2>
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<p>Hello @User.Identity.GetUserName()</p>
<ul>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul>
<li>
@Html.ActionLink("Login", "Login", "Account")
</li>
<li>
@Html.ActionLink("Register", "Register", "Account")
</li>
</ul>
}

然后AccountController控制器代码
private ApplicationSignInManager signInManager;
private ApplicationUserManager userManager; public ApplicationSignInManager SignInManager
{
get
{
return signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get { return userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
private set
{
userManager = value;
}
} [AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> 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<ActionResult> 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";
}
<h2>Login</h2>
@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SignInModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.RememberMe, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.CheckBoxFor(model => model.RememberMe)
@Html.ValidationMessageFor(model => model.RememberMe, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="SignIn" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("注册", "Register")
</div>

Register页面代码
@model IdentityDemo.Models.SignUpModel
@{
ViewBag.Title = "Register";
}
<h2>Register</h2>
@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SignUpModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.PasswordFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="SignUp" class="btn btn-default" />
</div>
</div>
</div>
}

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


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

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




Asp.Net MVC 5使用Identity之简单的注册和登陆的更多相关文章
- Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理
这是本人第一次写,写的不好的地方还忘包含.写这个的主要原因是想通过这个来学习下EF的CodeFirst模式,本来也想用AngularJs来玩玩的,但是自己只会普通的绑定,对指令这些不是很熟悉,所以就基 ...
- ASP.NET MVC 4 插件化架构简单实现-思路篇
用过和做过插件的都会了解插件的好处,园子里也有很多和讨论,但大都只些简单的加载程序集什么的,这里主要讨论的就是使用 ASP.NET MVC 4 来实现每个插件都可以完全从主站点剥离出来,即使只是一个插 ...
- ASP.NET MVC 4 插件化架构简单实现-实例篇
先回顾一下上篇决定的做法: 1.定义程序集搜索目录(临时目录). 2.将要使用的各种程序集(插件)复制到该目录. 3.加载临时目录中的程序集. 4.定义模板引擎的搜索路径. 5.在模板引擎的查找页面方 ...
- 使用asp.net mvc + entityframework + sqlServer 搭建一个简单的code first项目
步骤: 1. 创建一个asp.net mvc 项目 1.1 项目创建好结构如下 2 通过vs安装EntityFramework框架 install-package entityframework 3. ...
- Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理6
接下来先做角色这一板块的(增删改查),首先要新建一个Role控制器,在添加一个RoleList的视图.表格打算采用的是bootstrap的表格. using System; using System. ...
- Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理8
接下来做的是对页面的增删改查与页面与页面按钮之间的联系.先上代码和页面效果 using AuthorDesign.Web.App_Start.Common; using System; using S ...
- Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理10
今天把用户的菜单显示和页面的按钮显示都做好了,下面先来个效果图 接下来说下我实现的方法: 首先我在每个方法前面都加了这个属性, /// <summary> /// 表示当前Action请求 ...
- Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理1
首先给上项目的整体框架图:,这里我没有使用BLL,因为感觉太烦了就没有去使用. 那么接下来我们首先先去Model层中添加Model. 管理员类: using System; using System. ...
- Asp.Net MVC+BootStrap+EF6.0实现简单的用户角色权限管理4
首先先加个区域,名为Admin using System.Web.Mvc; namespace AuthorDesign.Web.Areas.Admin { public class AdminAre ...
随机推荐
- Sql server时间转时间long
DATEDIFF( S, '1970-01-01 00:00:00', a.endor_date ) - 8 * 60*60 ) actionTime, SELECT DATEADD(S,116070 ...
- maven打包的时候you are running on a JRE rather than a JDK?
解决方案.删除掉,然后重新添加. 然后remove掉 然后Add Library
- HDU 2296 Ring ( Trie图 && DP && DP状态记录)
题意 : 给出 m 个单词,每一个单词有一个权重,如果一个字符串包含了这些单词,那么意味着这个字符串拥有了其权重,问你构成长度为 n 且权重最大的字符串是什么 ( 若有权重相同的,则输出最短且字典序最 ...
- 【bzoj3262】陌上花开
题目描述: 有n朵花,每朵花有三个属性:花形(s).颜色(c).气味(m),又三个整数表示.现要对每朵花评级,一朵花的级别是它拥有的美丽能超过的花的数量.定义一朵花A比另一朵花B要美丽,当且仅当Sa& ...
- 把图片画到画布上,适应PC和移动端
画一张图片到画布上 <canvas id="myCanvas" width="1000px" height="200px" >您 ...
- 关于VS连接Oracle数据库提示:“尝试加载oracle客户端时引发badimage,如果在安装 32 位 Oracle 客户端组件的情况下以 64 位模式运行,将出现此问题”的解决方案。
错误一.关于VS连接Oracle数据库提示:“尝试加载oracle客户端时引发badimage,如果在安装 32 位 Oracle 客户端组件的情况下以 64 位模式运行,将出现此问题”的解决方案. ...
- 设计模式-Runoob:工厂模式
ylbtech-设计模式-Runoob:工厂模式 1.返回顶部 1. 工厂模式 工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一.这种类型的设计模式属于创建型模式,它提供 ...
- JSON基础,简单介绍
JSON(JavaScript Object Notation(记号.标记)) 是一种轻量级的数据交换格式.它基于JavaScript(Standard ECMA-262 3rd Edition - ...
- 002-Spring4 快速入门-项目搭建、基于注解的开发bean,Bean创建和装配、基于注解的开发bean,Bean初始化销毁、Bean装配,注解、Bean依赖注入
一.项目搭建 1.项目创建 eclipse→project explorer→new→Project→Maven Project 默认配置即可创建项目 2.spring配置 <dependenc ...
- 《图解设计模式》读书笔记9-1 Flyweight模式
目录 模式简介 示例代码 代码功能与实现思路 类图 代码 结果图示分析 模式角色和类图 角色 类图 拓展思路 对多个地方产生影响 什么要共享,什么不要共享 垃圾回收 模式简介 Flyweight是轻量 ...