在本节中,我将说明将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控制器用来管理用户登入登出注册等用户管理功能。

using System.Linq;
using EmptyMVC.Models.Account;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework; namespace EmptyMVC.Controllers
{
public class AccountController : Controller
{
//
// GET: /Account/
public ActionResult Register()
{
return View();
} [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// UserStore 默认构造函数会使用默认连接字符串: DefaultConnection
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = model.Name };
var result = manager.Create(user, model.Pwd);
if (result.Succeeded)
{
return Content(user.UserName + "创建成功,id:" + user.Id);
}
var erro = result.Errors.FirstOrDefault();
ModelState.AddModelError("",erro);
}
return View(model);
}
}
}

在这里需要引入一个ViewModel

using System.ComponentModel.DataAnnotations;

namespace EmptyMVC.Models.Account
{
public class RegisterModel
{
[Required]
[Display(Name = "用户名")]
public string Name { get; set; } [Required]
[StringLength(, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = )]
[DataType(DataType.Password)]
[Display(Name = "密码")]
public string Pwd { get; set; } [DataType(DataType.Password)]
[Display(Name = "确认密码")]
[Compare("Pwd", ErrorMessage = "密码和确认密码不匹配。")]
public string ConfirmPwd { get; set; }
}
}

连接字符串

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

创建视图

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

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

@model EmptyMVC.Models.Account.RegisterModel

@{
ViewBag.Title = "Register";
} <h2>Register</h2> @using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>RegisterModel</h4>
<hr />
@Html.ValidationSummary(true) <div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Pwd, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Pwd)
@Html.ValidationMessageFor(model => model.Pwd)
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.ConfirmPwd, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ConfirmPwd)
@Html.ValidationMessageFor(model => model.ConfirmPwd)
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="注册" class="btn btn-default" />
</div>
</div>
</div>
} <div>
@Html.ActionLink("回到首页", "Index")
</div> @section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

注意:这里最后通过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文件

配置(添加红色区域)

using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin; [assembly: OwinStartup(typeof(EmptyMVC.Startup))] namespace EmptyMVC
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// 有关如何配置应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=316888
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
}
}

添加登入登出方法

using System.Linq;
using System.Web;
using EmptyMVC.Models.Account;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security; namespace EmptyMVC.Controllers
{
public class AccountController : Controller
{
public ActionResult Index()
{
return View(User);
} public ActionResult LogOff()
{
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.SignOut();
return Redirect("Login");
} public ActionResult Login()
{
return View();
} [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
var user = userManager.Find(model.Name, model.Pwd);
if (user != null)
{
var authenticationManager = HttpContext.GetOwinContext().Authentication;
var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(userIdentity);
return LoginRedirect();
}
}
return View(model);
} //
// GET: /Account/
public ActionResult Register()
{
return View();
} [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// UserStore 默认构造函数会使用默认连接字符串: DefaultConnection
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = model.Name };
var result = manager.Create(user, model.Pwd);
if (result.Succeeded)
{
var authenticationManager = HttpContext.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
return LoginRedirect();
}
var erro = result.Errors.FirstOrDefault();
ModelState.AddModelError("", erro);
}
return View(model);
} private ActionResult LoginRedirect()
{
var url = HttpContext.Request["returnurl"];
if (string.IsNullOrEmpty(url))
return Redirect(Url.Action("Index"));
return Redirect(url);
}
}
}

AccountController

这里需要一个LoginModel

public class LoginModel
{
[Required]
[Display(Name = "用户名")]
public string Name { get; set; } [Required]
[StringLength(, ErrorMessage = "{0} 必须至少包含 {2} 个字符。", MinimumLength = )]
[DataType(DataType.Password)]
[Display(Name = "密码")]
public string Pwd { get; set; }
}

添加View

Login

@model EmptyMVC.Models.Account.LoginModel

@{
ViewBag.Title = "Login";
} <h2>Login</h2> @using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>LoginModel</h4>
<hr />
@Html.ValidationSummary(true) <div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Pwd, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Pwd)
@Html.ValidationMessageFor(model => model.Pwd)
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="登录" class="btn btn-default" />
</div>
</div>
</div>
} <div>
@Html.ActionLink("回到首页", "Index")
</div> @section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

Index

@using Microsoft.AspNet.Identity
@model System.Security.Principal.IPrincipal
@{
ViewBag.Title = "Index";
} <h2>Index</h2>
@if (Model.Identity.IsAuthenticated)
{
<h3>Hello @Model.Identity.GetUserName() !</h3>
using (Html.BeginForm("LogOff","Account"))
{
Html.AntiForgeryToken();
<input type="submit" value="退出"/>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("注册", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("登录", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}

开始登录

填写登录信息,点击登录

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

本文作者: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. android获取本机的IP地址和mac物理地址

    /获取本机IP地址 public String getLocalIpAddress() { WifiManager wifiManager = (WifiManager) getSystemServi ...

  2. [Android实例] 有关spinner 的item问题 谁能给解答下??

    [Android实例] 有关spinner 的item问题 (更多Android问题解决,Android开发讨论 请访问:http://www.eoeandroid.com/forum.php)

  3. redmine v3.02版的安装问题

    redmine v3.0.2版的安装问题 参考上次在朋友公司的云主机上安装的过程: 1. 下载 2. gem install bundler 3. bundle install 出现 rmagick ...

  4. 【jquery】一款不错的音频播放器——Amazing Audio Player

    前段时间分享了一款视频播放器,点击这里.今天介绍一款不错的音频播放器——Amazing Audio Player. 介绍: Amazing Audio Player 是一个使用很方便的 Windows ...

  5. Windows 8.1 Enterprise 下 安装 Eclipse 官方中文包后无法输入任何内容

    最新文章:Virson's Blog 官方下载的Eclipse解压后运行,然后通过repository方式安装了中文语言包,按提示后重启,重启后不能进行任何输入,解决该问题的方法就是将eclipse. ...

  6. WorkbookDesigner mvc里面返回file

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  7. Could not find the Visual SourceSafe Internet Web Service connection information for the specified database Would you like to launch the Visual sourceSafe connection wizard?

    今天同事遇到个奇怪问题,以前也遇到过,不过重新绑定一下就OK了,不知道为什么今天不行了. 错误提示:===============================================Cou ...

  8. spark MySQL jar 包

    /** * Created by songcl on 2016/6/24. */ import java.sql.DriverManager //val sqlContext = new org.ap ...

  9. Android UI开发第四十一篇——墨迹天气3.0引导界面及动画实现

    周末升级了墨迹天气,看着引导界面做的不错,模仿一下,可能与原作者的代码实现不一样,但是实现的效果还是差不多的.先分享一篇以前的文章,android动画的基础知识,<Android UI开发第十二 ...

  10. css3,background-clip/background-origin的使用场景,通俗讲解

    先不说background-clip/background-origin的用法,我们先来聊聊css背景方面的知识. <!DOCTYPE html> <html lang=" ...