您现在的位置是:网站首页> 编程资料编程资料
.net core2.0下使用Identity改用dapper存储数据(实例讲解)_实用技巧_
2023-05-24
240人已围观
简介 .net core2.0下使用Identity改用dapper存储数据(实例讲解)_实用技巧_
前言、
已经好多天没写博客了,鉴于空闲无聊之时又兴起想写写博客,也当是给自己做个笔记。过了这么些天,我的文笔还是依然那么烂就请多多谅解了。今天主要是分享一下在使用.net core2.0下的实际遇到的情况。在使用webapi时用了identity做用户验证。官方文档是的是用EF存储数据来使用dapper,因为个人偏好原因所以不想用EF。于是乎就去折腾。改成使用dapper做数据存储。于是就有了以下的经验。
一、使用Identity服务
先找到Startup.cs 这个类文件 找到 ConfigureServices 方法
services.AddIdentity().AddDefaultTokenProviders();//添加Identity services.AddTransient , CustomUserStore>(); services.AddTransient , CustomRoleStore>(); string connectionString = Configuration.GetConnectionString("SqlConnectionStr"); services.AddTransient (e => new SqlConnection(connectionString)); services.AddTransient ();
然后在 Configure 方法 的 app.UseMvc() 前加入下列代码,net core 1.0的时候是app.UseIdentity() 现在已经弃用改为以下方法。
//使用验证 app.UseAuthentication();
这里的 ApplicationUser 是自定义的一个用户模型 具体是继承 IdentityUser 继承它的一些属性
public class ApplicationUser :IdentityUser { public string AuthenticationType { get; set; } public bool IsAuthenticated { get; set; } public string Name { get; set; } }这里的 CustomUserStore 是自定义提供用户的所有数据操作的方法的类它需要继承三个接口:IUserStore,IUserPasswordStore,IUserEmailStore
IUserStore
IUserPasswordStore
IUserEmailStore
这里跟.net core 1.0的实现接口方式有点不同。需要多实现 IUserEmailStore 才能不报错
具体代码如下。以供大家参考。
CustomUserStore
using Microsoft.AspNetCore.Identity; using System; using System.Threading.Tasks; using System.Threading; namespace YepMarsCRM.Web.CustomProvider { /// /// This store is only partially implemented. It supports user creation and find methods. /// public class CustomUserStore : IUserStore, IUserPasswordStore, IUserEmailStore { private readonly DapperUsersTable _usersTable; public CustomUserStore(DapperUsersTable usersTable) { _usersTable = usersTable; } #region createuser public async Task CreateAsync(ApplicationUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return await _usersTable.CreateAsync(user); } #endregion public async Task DeleteAsync(ApplicationUser user, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return await _usersTable.DeleteAsync(user); } public void Dispose() { } public Task FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) { throw new NotImplementedException(); } public async Task FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (userId == null) throw new ArgumentNullException(nameof(userId)); Guid idGuid; if (!Guid.TryParse(userId, out idGuid)) { throw new ArgumentException("Not a valid Guid id", nameof(userId)); } return await _usersTable.FindByIdAsync(idGuid); } public async Task FindByNameAsync(string userName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); if (userName == null) throw new ArgumentNullException(nameof(userName)); return await _usersTable.FindByNameAsync(userName); } public Task GetEmailAsync(ApplicationUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.Email); } public Task GetEmailConfirmedAsync(ApplicationUser user, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task GetNormalizedEmailAsync(ApplicationUser user, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task GetNormalizedUserNameAsync(ApplicationUser user, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task GetPasswordHashAsync(ApplicationUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.PasswordHash); } public Task GetUserIdAsync(ApplicationUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.Id.ToString()); } public Task GetUserNameAsync(ApplicationUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.UserName); } public Task HasPasswordAsync(ApplicationUser user, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetEmailAsync(ApplicationUser user, string email, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetEmailConfirmedAsync(ApplicationUser user, bool confirmed, CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task SetNormalizedEmailAsync(ApplicationUser user, string normalizedEmail, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) throw new ArgumentNullException(nameof(user)); if (normalizedEmail == null) throw new ArgumentNullException(nameof(normalizedEmail)); user.NormalizedEmail = normalizedEmail; return Task.FromResult 二、使用使用dapper做数据存储
接着就是使用dapper做数据存储。该类的方法都是通过 CustomUserStore 调用去操作数据库的。具体代码如下。根据实际的用户表去操作dapper即可。
DapperUsersTable
using Microsoft.AspNetCore.Identity; using System.Threading.Tasks; using System.Threading; using System.Data.SqlClient; using System; using Dapper; using YepMarsCRM.Enterprise.DataBase.Model; using YepMarsCRM.Enterprise.DataBase.Data; namespace YepMarsCRM.Web.CustomProvider { public class DapperUsersTable { private readonly SqlConnection _connection; private readonly Sys_AccountData _sys_AccountData; public DapperUsersTable(SqlConnection connection) { _connection = connection; _sys_AccountData = new Sys_AccountData(); } private Sys_Account ApplicationUserToAccount(ApplicationUser user) { return new Sys_Account { Id = user.Id, UserName = user.UserName, PasswordHash = user.PasswordHash, Email = user.Email, EmailConfirmed = user.EmailConfirmed, PhoneNumber = user.PhoneNumber, PhoneNumberConfirmed = user.PhoneNumberConfirmed, LockoutEnd = user.LockoutEnd?.DateTime, LockoutEnabled = user.LockoutEnabled, AccessFailedCount = user.AccessFailedCount, }; } #region createuser public async Task CreateAsync(ApplicationUser user) { int rows = await _sys_AccountData.InsertAsync(ApplicationUserToAccount(user)); if (rows > 0) { return IdentityResult.Success; } return IdentityResult.Failed(new IdentityError { Description = $"Could not insert user {user.Email}." }); } #endregion public async Task DeleteAsync(ApplicationUser user) { //string sql = "DELETE FROM Sys_Account WHERE Id = @Id"; //int rows = await _connection.ExecuteAsync(sql, new { user.Id }); int rows = await _sys_AccountData.DeleteForPKAsync(ApplicationUserToAccount(user)); if (rows > 0) { return IdentityResult.Success; } return IdentityResult.Failed(new IdentityError { Description = $"Could not delete user {user.Email}." }); } public async Task FindByIdAsync(Guid userId) { string sql = "SELECT * FROM Sys_Account WHERE Id = @Id;"; return await _connection.QuerySingleOrDefaultAsync(sql, new { Id = userId }); } public async Task FindByNameAsync(string userName) { string sql = "SELECT * FROM Sys_Account WHERE UserName = @UserName;"; return await _connection.QuerySingleOrDefaultAsync(sql, new { UserName = userName }); //var user = new ApplicationUser() { UserName = userName, Email = userName, EmailConfirmed = false }; //user.PasswordHash = new PasswordHasher().HashPassword(user, "test"); //return awa
相关内容
- VS2017 安装打包插件的图文教程_实用技巧_
- visual studio 2015+opencv2.4.13配置教程_实用技巧_
- OpenCV 3.1.0+VS2015开发环境配置教程_实用技巧_
- VS2015下OpenCV配置方法图文教程_实用技巧_
- win10下vs2015配置Opencv3.1.0详细过程_实用技巧_
- Visual Studio 2010配置OpenCV的方法_实用技巧_
- 使用 Visual Studio 的“代码度量值”来改进代码质量_实用技巧_
- .NET读写Excel工具Spire.Xls使用 重量级的Excel图表功能(5)_实用技巧_
- .NET读写Excel工具Spire.Xls使用 对数据操作与控制(4)_实用技巧_
- .NET读写Excel工具Spire.Xls使用 Excel单元格控制(3)_实用技巧_
点击排行
本栏推荐
