使用用户管理器之用户注册

配置数据库在appsettings.json,系统默认生成的是连接到sqlserver服务中的数据库。如果想连接到.mdb文件上(便携型数据库)请参照我的另一篇博文《.net 和 core 数据库连接字符串 》中关于《Asp.net Core 数据库离线文件的连接(特别感谢“张不水”兄的大力帮助。)》的部分。

1、修改密码强度和用户邮箱验证规则:(微软官方示例采用的是后面的方式)

打开Startup.cs,在public class Startup{}内找public void ConfigureServices(IServiceCollection services){}修改services.AddIdentity<ApplicationUser, IdentityRole>()为如下代码:

             services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
// 配置身份选项
// 密码配置
options.Password.RequireDigit = false;//是否需要数字(0-9).
options.Password.RequiredLength = ;//设置密码长度最小为6
options.Password.RequireNonAlphanumeric = false;//是否包含非字母或数字字符。
options.Password.RequireUppercase = false;//是否需要大写字母(A-Z).
options.Password.RequireLowercase = false;//是否需要小写字母(a-z). // 锁定设置
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes();//账户锁定时长30分钟
options.Lockout.MaxFailedAccessAttempts = ;//10次失败的尝试将账户锁定 // Cookie常用设置
options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays();//Cookie 保持有效的时间150天。
options.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";//在进行登录时自动重定向。
options.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOff";//在进行注销时自动重定向。 //cookie扩展设置(通常不用)
options.Cookies.ApplicationCookie.CookieName = "YouAppCookieName";//用于保持身份的 Cookie 名称。 默认值为“.AspNet.Cookies”。
options.Cookies.ApplicationCookie.AccessDeniedPath = "/Account/AccessDenied";//被拒绝访问或路径无效后的重定向。
options.Cookies.ApplicationCookie.AutomaticAuthenticate = true;//自动认证
options.Cookies.ApplicationCookie.AuthenticationScheme = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;//选定认证方案的名称。
options.Cookies.ApplicationCookie.ReturnUrlParameter = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.ReturnUrlParameter;//登陆或退出后执行动作返回到原来的地址。 // 用户设置
options.User.RequireUniqueEmail = true; //是否Email地址必须唯一
})

或者在AddDefaultTokenProviders();的后面   services.AddMvc();前面添加如下代码(微软官方示例代码形式,推荐)

 services.Configure<IdentityOptions>(options =>
{
// 配置身份选项
// 密码配置
options.Password.RequireDigit = false;//是否需要数字(0-9).
options.Password.RequiredLength = ;//设置密码长度最小为6
options.Password.RequireNonAlphanumeric = false;//是否包含非字母或数字字符。
options.Password.RequireUppercase = false;//是否需要大写字母(A-Z).
options.Password.RequireLowercase = false;//是否需要小写字母(a-z). // 锁定设置
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes();//账户锁定时长30分钟
options.Lockout.MaxFailedAccessAttempts = ;//10次失败的尝试将账户锁定 // Cookie常用设置
options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays();//Cookie 保持有效的时间150天。
options.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn";//在进行登录时自动重定向。
options.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOff";//在进行注销时自动重定向。 // 用户设置
options.User.RequireUniqueEmail = true; //是否Email地址必须唯一
});

2、打开Controllers目录下的AccountController.cs

找到 public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) (110行)这下面的var user = new ApplicationUser { UserName = model.Email, Email = model.Email };(115行)这里两个参数都是绑定的email。

改为var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };

更改后vs会提示下红波浪线(错误),选择纠错为“生成属性”的哪一项。注意:自动生成会是public string UserName { get; internal set; } 必须把internal set改为set,否则后期无法获取到值。

  

3、修改用户注册的数据模型:修改Models文件夹下AccountViewModels目录下RegisterViewModel.cs模型内的public class RegisterViewModel 中添加   public string UserName { get; set; },好了在上面堆你想要的规则吧。

         [Required]
[StringLength(, ErrorMessage = "{0} 必须至少包含 {2} 个字符,最多20个字符。", MinimumLength = )]
[Display(Name = "用户账号")]
[DataType(DataType.Text)]
[RegularExpression("^[a-zA-Z0-9_]{6,20}$", ErrorMessage = "用户名由字母或数字组成。")]
public string UserName { get; set; }

为方便大家这是修改好的代码

 public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "电子信箱")]
public string Email { get; set; } [Required]
[StringLength(, ErrorMessage = "请在 {0} 填入最少 {2} 最大 {1} 个字符。", MinimumLength = )]
[DataType(DataType.Password)]
[Display(Name = "用户密码")]
public string Password { get; set; } [DataType(DataType.Password)]
[Display(Name = "确认密码")]
[Compare("Password", ErrorMessage = "请确保和用户密码一致。")]
public string ConfirmPassword { get; set; } [Required]
[StringLength(, ErrorMessage = "请在 {0} 填入最少 {2} 最大 {1} 个字符。", MinimumLength = )]
[Display(Name = "用户账号")]
[DataType(DataType.Text)]
[RegularExpression("^[a-zA-Z0-9_]{6,20}$", ErrorMessage = "用户名由字母或数字组成。")]
public string UserName { get; set; }
}

4、在Views文件夹的Account中的register.cshtml文件中添加“用户账号”代码:

     <div class="form-group">
<label asp-for="UserName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="UserName" class="form-control" />
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</div>

大家可以看下,这里的代码和之前的已经不一样了,随着TagHelper的更新,这里的代码也变为 asp-for了。TagHelper的资料请参阅这里

5、修改login,因为改为了用户名注册,如果还用email登陆的话,一定出现错误。

首先在ViewModels文件夹下找LoginViewModel.cs,在模型内添加 public string UesrName { get; set; },好了在上面堆你想要的规则吧。

  [Required]
[StringLength(, ErrorMessage = "{0} 必须至少包含 {2} 个字符,最多20个字符。", MinimumLength = )]
[Display(Name = "用户账号")]
[DataType(DataType.Text)]
[RegularExpression("^[a-zA-Z0-9_]{6,20}$", ErrorMessage ="用户名由字母或数字组成。")]
public string UserName { get; set; }

接着把email模型项去掉或者注释掉,否则你登陆不上去且还不给提示。

6、在Views文件夹中的login.cshtml文件中原来为“email”的地方改为“UserName”。

7、打开AccountController.cs文件,找到  public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) 这个方法

把  var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);

改为var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);

现在,各位可以试试了。

.net core 1.0 中的asp.net identity 基本使用(一)的更多相关文章

  1. .net core 1.0 中的asp.net identity 的基本使用 序言

    2016年6月底,微软发不了vs2015 up3,在这个版本中,微软做了一些改变,本人目前也尚在学习使用之中,现把学习和使用的心得写出来,错误之处请大家指正. 开发环境:vs2015 UP3   项目 ...

  2. .net core 1.0 中的asp.net identity 基本使用(二)

    一.重写(覆盖)身份验证数据类型 1.修改Models目录中的ApplicationUser.cs类文件,如下 namespace xxxx.Models { //将应用程序用户的属性添加到应用程序 ...

  3. 避免在ASP.NET Core 3.0中为启动类注入服务

    本篇是如何升级到ASP.NET Core 3.0系列文章的第二篇. Part 1 - 将.NET Standard 2.0类库转换为.NET Core 3.0类库 Part 2 - IHostingE ...

  4. ASP.NET Core 1.0 中的依赖项管理

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  5. 在ASP.NET Core 1.0中如何发送邮件

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:目前.NET Core 1.0中并没有提供SMTP相关的类库,那么要如何从ASP.NE ...

  6. ASP.NET Core 1.0 中使用 Swagger 生成文档

    github:https://github.com/domaindrivendev/Ahoy 之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1. ...

  7. 用ASP.NET Core 1.0中实现邮件发送功能

    准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit 好东西一定要试 ...

  8. 在ASP.NET Core 2.0中使用CookieAuthentication

    在ASP.NET Core中关于Security有两个容易混淆的概念一个是Authentication(认证),一个是Authorization(授权).而前者是确定用户是谁的过程,后者是围绕着他们允 ...

  9. 如何在ASP.NET Core 2.0中使用Razor页面

    如何在ASP.NET Core 2.0中使用Razor页面  DotNetCore2017-11-22 14:49 问题 如何在ASP.NET Core 2.0中使用Razor页面 解 创建一个空的项 ...

随机推荐

  1. java26

    1:网络编程(理解)    (1)网络编程:用Java语言实现计算机间数据的信息传递和资源共享    (2)网络编程模型    (3)网络编程的三要素        A:IP地址           ...

  2. LeetCode 26 Remove Duplicates from Sorted Array

    Problem: Given a sorted array, remove the duplicates in place such that each element appear only onc ...

  3. jQuery的.bind()、.live()和.delegate()的区别

    参考:http://kb.cnblogs.com/page/94469/ 摘要:jQuery的.bind()..live()和.delegate()之间的区别并非总是那么明显的,然而,如果我们对所有的 ...

  4. yii 常用的多表查询

    return $this->model()->getDbConnection()->createCommand() ->select("t.type,t.title, ...

  5. Python WebDriver自动化测试

    转载来自: http://www.cnblogs.com/fnng/p/3160606.html Webdriver Selenium 是 ThroughtWorks 一个强大的基于浏览器的开源自动化 ...

  6. 【leetcode】Remove Element

    题目概述: Given an array and a value, remove all instances of that value in place and return the new len ...

  7. [转]Ubuntu 12.04中文输入法的安装

    Ubuntu上的输入法主要有小小输入平台(支持拼音/二笔/五笔等),Fcitx,Ibus,Scim等.其中Scim和Ibus是输入法框架. 在Ubuntu的中文系统中自带了中文输入法,通过Ctrl+S ...

  8. java.lang.OutOfMemoryError: bitmap size exceeds VM budget解决方法

    1 BitmapFactory.decodeFile(imageFile); 用BitmapFactory解码一张图片时,有时会遇到该错误.这往往是由于图片过大造成的.要想正常使用,则需要分配更少的内 ...

  9. SpringMvc的创建流程以及2种加载配置文件的方式

    1.首先创建个web项目,第一步导入相应的jar包,并且buildtoPath 2.用elipse或myeclipse点击进入web.xml中 按住 Alt+ / 有个提示 找到前面带 #Dispat ...

  10. 疯狂房价"逼死"年轻人,别指望中国未来能出人才了

    社会高房价,杀死那个学者 --北京青年学者生存侧记 这一轮,房价又上涨了,只有更疯狂. 几年前,北京三环内的房价突破5万,世人惊呼:没几年,四环5万了,五环5万了:这一轮,北京城乡结合部,哪怕脏乱差之 ...