ASP.NET MVC5网站开发用户登录、注销(五)

所属分类: 网络编程 / ASP.NET 阅读数: 698
收藏 0 赞 0 分享

本文实例为大家分享了ASP.NET MVC5网站开发用户登录、注销的具体方法,供大家参考,具体内容如下

一、创建ClaimsIdentity

ClaimsIdentity(委托基于声明的标识)是在ASP.NET Identity身份认证系统的登录时要用到,我们在UserService中来生成它。

1、打开IBLL项目InterfaceUserService接口,添加接口方法ClaimsIdentity CreateIdentity(User user, string authenticationType);

2、打开BLL项目的UserService类,添加CreateIdentity方法的实现代码

public ClaimsIdentity CreateIdentity(User user, string authenticationType)
 {
 ClaimsIdentity _identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
 _identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
 _identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()));
 _identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity"));
 _identity.AddClaim(new Claim("DisplayName", user.DisplayName));
 return _identity;
 }

二、获取AuthenticationManager(认证管理器)

打开Ninesky.Web项目 Member区域的UserController,添加AuthenticationManager属性,在HttpContext.GetOwinContext()中获取这个属性。

#region 属性
 private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } }
 #endregion

三、创建登录视图模型

Member区域的模型文件夹添加视图模型

using System.ComponentModel.DataAnnotations;

namespace Ninesky.Web.Areas.Member.Models
{
 /// <summary>
 /// 登录模型
 /// <remarks>
 /// 创建:2014.02.16
 /// </remarks>
 /// </summary>
 public class LoginViewModel
 {
 /// <summary>
 /// 用户名
 /// </summary>
 [Required(ErrorMessage = "必填")]
 [StringLength(20, MinimumLength = 4, ErrorMessage = "{2}到{1}个字符")]
 [Display(Name = "用户名")]
 public string UserName { get; set; }

 /// <summary>
 /// 密码
 /// </summary>
 [Required(ErrorMessage = "必填")]
 [Display(Name = "密码")]
 [StringLength(20, MinimumLength = 6, ErrorMessage = "{2}到{1}个字符")]
 [DataType(DataType.Password)]
 public string Password { get; set; }

 /// <summary>
 /// 记住我
 /// </summary>
 [Display(Name = "记住我")]
 public bool RememberMe { get; set; }
 }
}

四、创建登录页面

在UserCcontroller中添加(string returnUrl) action

/// <summary>
 /// 用户登录
 /// </summary>
 /// <param name="returnUrl">返回Url</param>
 /// <returns></returns>
 public ActionResult Login(string returnUrl)
 {
 return View();
 }

右键添加强类型视图,模型为LoginViewModel

@model Ninesky.Web.Areas.Member.Models.LoginViewModel

@{
 ViewBag.Title = "会员登录";
}

@using (Html.BeginForm()) 
{
 @Html.AntiForgeryToken()
 
 <div class="form-horizontal">
 <h4>会员登录</h4>
 <hr />
 @Html.ValidationSummary(true)

 <div class="form-group">
 @Html.LabelFor(model => model.UserName, new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @Html.EditorFor(model => model.UserName)
 @Html.ValidationMessageFor(model => model.UserName)
 </div>
 </div>

 <div class="form-group">
 @Html.LabelFor(model => model.Password, new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @Html.EditorFor(model => model.Password)
 @Html.ValidationMessageFor(model => model.Password)
 </div>
 </div>

 <div class="form-group">
 @Html.LabelFor(model => model.RememberMe, new { @class = "control-label col-md-2" })
 <div class="col-md-10">
 @Html.EditorFor(model => model.RememberMe)
 @Html.ValidationMessageFor(model => model.RememberMe)
 </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>
}

@section Scripts {
 @Scripts.Render("~/bundles/jqueryval")
}

效果

五、创建用户登录处理action

在UserCcontroller中添加 httppost类型的 Login action中先用ModelState.IsValid看模型验证是否通过,没通过直接返回,通过则检查用户密码是否正确。用户名密码正确用CreateIdentity方法创建标识,然后用SignOut方法清空Cookies,然后用SignIn登录。

[ValidateAntiForgeryToken]
 [HttpPost]
 public ActionResult Login(LoginViewModel loginViewModel)
 {
 if(ModelState.IsValid)
 {
 var _user = userService.Find(loginViewModel.UserName);
 if (_user == null) ModelState.AddModelError("UserName", "用户名不存在");
 else if (_user.Password == Common.Security.Sha256(loginViewModel.Password))
 {
 var _identity = userService.CreateIdentity(_user, DefaultAuthenticationTypes.ApplicationCookie);
 AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
 AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = loginViewModel.RememberMe }, _identity);
 return RedirectToAction("Index", "Home");
 }
 else ModelState.AddModelError("Password", "密码错误");
 }
 return View();
 }

六、修改用户注册代码

让用户注册成功后直接登录

七、注销

在UserCcontroller中添加在Logout action

/// <summary>
 /// 登出
 /// </summary>
 /// <returns></returns>
 public ActionResult Logout()
 {
 AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
 return Redirect(Url.Content("~/"));
 }

本文已被整理到了《ASP.NET MVC网站开发教程》,欢迎大家学习阅读,更多内容还可以参考ASP.NET MVC5网站开发专题学习。

本文主要是用到了ClaimsIdentity(基于声明的标识)、AuthenticationManager的SignOut、SignIn方法。希望对大家实现用户注册和注销有所帮助。

更多精彩内容其他人还在看

ASP.NET 水晶报表打印功能实现代码

ASP.NET下的水晶报表打印,据我所知有以下几种办法可以打印
收藏 0 赞 0 分享

ASP.Net 图片存入数据库的实现代码

在很多时候,我们有这样的需求:把图片存入到数据库当中。在一些应用程序中,我们可能有一些敏感的资料,由于存储在文件系统(file system)中的东西,将很容易被某些用户盗取,所以这些数据不能存放在文件系统中。
收藏 0 赞 0 分享

让Silverlight 2.0动画动起来Making Silverlight 2.0 animation Start(不能运动原因)

Microsoft Expression Blend 2 制作动画个人感觉倒像3DMAX 可以自动捕捉关键帧
收藏 0 赞 0 分享

asp.net Reporting Service在Web Application中的应用

由于我们这个项目中使用微软的报表服务(Reporting Services)作为报表输出工具,本人也对它进行一点点研究,虽没有入木三分,但这点知识至少可以在大部分Reporting Service的场景中应用。
收藏 0 赞 0 分享

C# 文件上传 默认最大为4M的解决方法

.net中默只能上传小于4m的文件,大于4M将无法显示页面.那么如何设置来使imputfile能上传更大的文件呢
收藏 0 赞 0 分享

asp.net 购物车实现详细代码

asp.net 购物车实现详细代码
收藏 0 赞 0 分享

asp.net repeater实现批量删除时注册多选框id到客户端

repeater批量删除时注册多选框id到客户端的实现代码
收藏 0 赞 0 分享

asp.net aspnetpager分页统计时与实际不符的解决办法

最近分页方面根据实际需要修改了一些函数
收藏 0 赞 0 分享

iis 服务器应用程序不可用的解决方法

访问页面时提示 服务器应用程序不可用,大家可以按照下面的方法重新注册下,应该能好点
收藏 0 赞 0 分享

asp.net button 绑定多个参数

asp.net button 绑定多个参数的代码
收藏 0 赞 0 分享
查看更多