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 ...
随机推荐
- Last Defence
Given two integers A and B. Sequence S is defined as follow: • S0 = A •S1 = B • Si = |Si−1 − Si−2| f ...
- VMware 15 搭建MacOS 10.14教程
写于2018.12.23 教程原文链接:https://pan.baidu.com/s/1wvNYg_MQH_lwewKbpCQ5_Q ———————————————————————————————— ...
- 逻辑回归模型(Logistic Regression, LR)--分类
逻辑回归(Logistic Regression, LR)模型其实仅在线性回归的基础上,套用了一个逻辑函数,但也就由于这个逻辑函数,使得逻辑回归模型成为了机器学习领域一颗耀眼的明星,更是计算广告学的核 ...
- C++编译-链接错误集合
1,无法解析的外部符号,链接错误,原因:没找到某个符号(变量或函数)的定义体,一般是对应函数没实现,或第三方库没有添加到工程设置中 2,重复链接链接错误,一个定义体(实现体)被多个CPPP文件包含,导 ...
- Window7 系统下重新建立一个新分区
为了方便使用,准备在原来分区上再分割出一个分区,步骤如下 首先右击计算机,选择管理打开计算机管理窗口,选择磁盘管理,当前窗口右侧会出现当前计算机所有已存在的分区列表. 选择要进行分区的磁盘,右击选择压 ...
- DAY 6 上午
如果不是割点,答案减少2(n-1) 如果删去割点,删去之后整个图分成多个连通块 每一个联通块的大小*其他连通块的大小之和 先求出缩点之后的树 加尽可能少的边使树变成一个边双 找出树上的所有叶子节点(度 ...
- (转) intellij idea部署web项目时的位置(Tomcat)
这篇文章说的比较好: 原文地址:https://blog.csdn.net/zmx729618/article/details/78340566 1.当你项目启动的时候console能看到项目运行的位 ...
- js高级写法
名称 一般写法 优化 取整(不四舍五入) parseInt(a,10); //Before Math.floor(a); //Before a>>0; //Before ~~a; //Af ...
- 《图解设计模式》读书笔记9-2 Proxy模式
目录 Proxy模式 示例程序 程序描述 类图 程序 角色和类图 角色 模式类图 思路拓展 提升速度 代理与委托 Http代理 与其他模式的关联 Decorator模式 Proxy模式 Proxy是代 ...
- Jmeter之完整的HTTP接口测试
目前很多接口都是基于HTTP的,所以针对HTTP接口测试的了解很重要,下面就简单说明一下,一个基于Jmeter上HTTP接口测试需要的内容. 一.一个HTTP接口测试需要最基础的内容 如下: 简单说明 ...