目录

  1. 前言
  2. 使用dapper做数据层调用
  3. 使用T4模板生成
  4. 使用缓存
  5. 使用swagger做接口文档(非restful)
  6. 使用identity做身份认证
  7. 使用jwt做身份认证
  8. 使用CORS跨域
  9. 调用webservice服务
  10. 接入支付宝与微信支付
  11. 使用epplus. core操作excel

前言、

  已经好多天没写博客了,鉴于空闲无聊之时又兴起想写写博客,也当是给自己做个笔记。过了这么些天,我的文笔还是依然那么烂就请多多谅解了。今天主要是分享一下在使用.net core2.0下的实际遇到的情况。在使用webapi时用了identity做用户验证。官方文档是的是用EF存储数据来使用dapper,因为个人偏好原因所以不想用EF。于是乎就去折腾。改成使用dapper做数据存储。于是就有了以下的经验。

一、使用Identity服务

  先找到Startup.cs 这个类文件 找到 ConfigureServices 方法

services.AddIdentity<ApplicationUser, ApplicationRole>().AddDefaultTokenProviders();//添加Identity
services.AddTransient<IUserStore<ApplicationUser>, CustomUserStore>();
services.AddTransient<IRoleStore<ApplicationRole>, CustomRoleStore>();
string connectionString = Configuration.GetConnectionString("SqlConnectionStr");
services.AddTransient<SqlConnection>(e => new SqlConnection(connectionString));
services.AddTransient<DapperUsersTable>();

  然后在 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 是自定义提供用户的所有数据操作的方法的类它需要继承三个接口:IUserStoreIUserPasswordStoreIUserEmailStore

  IUserStore<TUser>接口是在用户存储中必须实现的唯一接口。 它定义了用于创建、 更新、 删除和检索用户的方法。

  IUserPasswordStore<TUser>接口定义实现以保持经过哈希处理的密码的方法。 它包含用于获取和设置工作经过哈希处理的密码,以及用于指示用户是否已设置密码的方法的方法。

  IUserEmailStore<TUser>接口定义实现以存储用户电子邮件地址的方法。 它包含用于获取和设置的电子邮件地址和是否确认电子邮件的方法。

  这里跟.net core 1.0的实现接口方式有点不同。需要多实现 IUserEmailStore 才能不报错

  具体代码如下。以供大家参考。

using Microsoft.AspNetCore.Identity;
using System;
using System.Threading.Tasks;
using System.Threading; namespace YepMarsCRM.Web.CustomProvider
{
/// <summary>
/// This store is only partially implemented. It supports user creation and find methods.
/// </summary>
public class CustomUserStore : IUserStore<ApplicationUser>,
IUserPasswordStore<ApplicationUser>,
IUserEmailStore<ApplicationUser>
{
private readonly DapperUsersTable _usersTable; public CustomUserStore(DapperUsersTable usersTable)
{
_usersTable = usersTable;
} #region createuser
public async Task<IdentityResult> 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<IdentityResult> 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<ApplicationUser> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken)
{
throw new NotImplementedException();
} public async Task<ApplicationUser> 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<ApplicationUser> FindByNameAsync(string userName,
CancellationToken cancellationToken = default(CancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
if (userName == null) throw new ArgumentNullException(nameof(userName)); return await _usersTable.FindByNameAsync(userName);
} public Task<string> GetEmailAsync(ApplicationUser user, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.Email);
} public Task<bool> GetEmailConfirmedAsync(ApplicationUser user, CancellationToken cancellationToken)
{
throw new NotImplementedException();
} public Task<string> GetNormalizedEmailAsync(ApplicationUser user, CancellationToken cancellationToken)
{
throw new NotImplementedException();
} public Task<string> GetNormalizedUserNameAsync(ApplicationUser user, CancellationToken cancellationToken)
{
throw new NotImplementedException();
} public Task<string> GetPasswordHashAsync(ApplicationUser user, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.PasswordHash);
} public Task<string> GetUserIdAsync(ApplicationUser user, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.Id.ToString());
} public Task<string> GetUserNameAsync(ApplicationUser user, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (user == null) throw new ArgumentNullException(nameof(user)); return Task.FromResult(user.UserName);
} public Task<bool> 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<object>(null);
} public Task SetNormalizedUserNameAsync(ApplicationUser user, string normalizedName, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (user == null) throw new ArgumentNullException(nameof(user));
if (normalizedName == null) throw new ArgumentNullException(nameof(normalizedName)); user.NormalizedUserName = normalizedName;
return Task.FromResult<object>(null);
} public Task SetPasswordHashAsync(ApplicationUser user, string passwordHash, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (user == null) throw new ArgumentNullException(nameof(user));
if (passwordHash == null) throw new ArgumentNullException(nameof(passwordHash)); user.PasswordHash = passwordHash;
return Task.FromResult<object>(null); } public Task SetUserNameAsync(ApplicationUser user, string userName, CancellationToken cancellationToken)
{
throw new NotImplementedException();
} public Task<IdentityResult> UpdateAsync(ApplicationUser user, CancellationToken cancellationToken)
{
return _usersTable.UpdateAsync(user);
}
}
}

CustomUserStore

二、使用使用dapper做数据存储

  接着就是使用dapper做数据存储。该类的方法都是通过 CustomUserStore 调用去操作数据库的。具体代码如下。根据实际的用户表去操作dapper即可。

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<IdentityResult> CreateAsync(ApplicationUser user)
{
int rows = await _sys_AccountData.InsertAsync(ApplicationUserToAccount(user));
if (rows > )
{
return IdentityResult.Success;
}
return IdentityResult.Failed(new IdentityError { Description = $"Could not insert user {user.Email}." });
}
#endregion public async Task<IdentityResult> 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 > )
{
return IdentityResult.Success;
}
return IdentityResult.Failed(new IdentityError { Description = $"Could not delete user {user.Email}." });
} public async Task<ApplicationUser> FindByIdAsync(Guid userId)
{
string sql = "SELECT * FROM Sys_Account WHERE Id = @Id;";
return await _connection.QuerySingleOrDefaultAsync<ApplicationUser>(sql, new
{
Id = userId
});
} public async Task<ApplicationUser> FindByNameAsync(string userName)
{
string sql = "SELECT * FROM Sys_Account WHERE UserName = @UserName;"; return await _connection.QuerySingleOrDefaultAsync<ApplicationUser>(sql, new
{
UserName = userName
}); //var user = new ApplicationUser() { UserName = userName, Email = userName, EmailConfirmed = false };
//user.PasswordHash = new PasswordHasher<ApplicationUser>().HashPassword(user, "test");
//return await Task.FromResult(user);
} public async Task<IdentityResult> UpdateAsync(ApplicationUser applicationUser)
{
var user = ApplicationUserToAccount(applicationUser);
var result = await _sys_AccountData.UpdateForPKAsync(user);
if (result > )
{
return IdentityResult.Success;
}
return IdentityResult.Failed(new IdentityError { Description = $"Could not update user {user.Email}." });
}
}
}

DapperUsersTable

三、使用UserManager、SignInManager验证操作

  新建一个 AccountController 控制器 并在构造函数中获取 依赖注入的对象 UserManager 与 SignInManager 如下:

  [Authorize]
  public class AccountController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger; public AccountController(UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_logger = loggerFactory.CreateLogger<AccountController>();
}
}

  SignInManager 是提供用户登录登出的API ,UserManager 是提供用户管理的API。

  接着来实现一下简单的登录登出。

        /// <summary>
/// 登录
/// </summary>
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(ReqLoginModel req)
{
var json = new JsonResultModel<object>();
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(req.UserName, req.Password, isPersistent: true, lockoutOnFailure: false);
if (result.Succeeded)
{
json.code = "";
json.message = "登录成功";
}
else
{
json.code = "";
json.message = "登录失败";
}
if (result.IsLockedOut)
{
json.code = "";
json.message = "账户密码已错误3次,账户被锁定,请30分钟后再尝试";
}
}
else
{
var errorMessges = ModelState.GetErrorMessage();
json.code = "";
json.message = string.Join(",", errorMessges);
}
return json.ToJsonResult();
}
        /// <summary>
/// 登出
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> LogOut()
{await _signInManager.SignOutAsync();
var json = new JsonResultModel<object>()
{
code = "",
data = null,
message = "登出成功",
remark = string.Empty
};
return json.ToJsonResult();
}

四、使用Identity配置

  在 ConfigureServices 方法中加入

            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.Password.RequiredUniqueChars = 6; // 锁定设置
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes();//账户锁定时长30分钟
options.Lockout.MaxFailedAccessAttempts = ;//10次失败的尝试将账户锁定
//options.Lockout.AllowedForNewUsers = true; // 用户设置
options.User.RequireUniqueEmail = false; //是否Email地址必须唯一
}); services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
//options.Cookie.Expiration = TimeSpan.FromMinutes(30);//30分钟
options.Cookie.Expiration = TimeSpan.FromHours();//12小时
options.LoginPath = "/api/Account/NotLogin"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
//options.LogoutPath = "/api/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
//options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
});

五、其他

  在实现的过程中遇到一些小状况。例如Identity不生效。是因为未在app.UseMvc() 之前使用造成的。 如果未登录会造成跳转。后来查看了.net core Identity 的源码后 发现 如果是ajax情况下 不会跳转而时 返回401的状态码页面。

然后就是Idenetity的密码加密 是用 PasswordHasher 这个类去加密的。如果想用自己的加密方式。只能通过继承接口去更改原本的方式。然后大致说到这么些。也当是给自己做做笔记。做得不好请大家多给点意见。多多谅解。谢谢。

.net core2.0下使用Identity改用dapper存储数据的更多相关文章

  1. Net Core2.0下使用Dapper

    Net Core2.0下使用Dapper 今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和 ...

  2. .Net Core2.0下使用Dapper遇到的问题

    今天成功把.Net Framework下使用Dapper进行封装的ORM成功迁移到.Net Core 2.0上,在迁移的过程中也遇到一些很有意思的问题,值得和大家分享一下.下面我会还原迁移的每一个过程 ...

  3. .net core2.0下Ioc容器Autofac使用

    .net core发布有一段时间了,最近两个月开始使用.net core2.0开发项目,大大小小遇到了一些问题.准备写个系列介绍一下是如何解决这些问题以及对应技术.先从IOC容器Autofac开始该系 ...

  4. net core体系-web应用程序-4asp.net core2.0 项目实战(1)-12基于cookie登录授权认证并实现前台会员、后台管理员同时登录

    1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...

  5. NET Core2.0 Memcached踩坑,基于EnyimMemcachedCore整理MemcachedHelper帮助类。

    DotNetCore2.0下使用memcached缓存. Memcached目前微软暂未支持,暂只支持Redis,由于项目历史原因,先用博客园开源项目EnyimMemcachedCore,后续用到的时 ...

  6. net core体系-web应用程序-4asp.net core2.0 项目实战(1)-10项目各种全局帮助类

    本文目录 1.  前沿2.CacheHelper基于Microsoft.Extensions.Caching.Memory封装3.XmlHelper快速操作xml文档4.SerializationHe ...

  7. net core体系-web应用程序-4asp.net core2.0 项目实战(1)-9项目各种全局帮助类

    本文目录 1.  前沿2.CacheHelper基于Microsoft.Extensions.Caching.Memory封装3.XmlHelper快速操作xml文档4.SerializationHe ...

  8. net core体系-web应用程序-4asp.net core2.0 项目实战(1)-8项目加密解密方案

    本文目录1. 摘要2. MD5加密封装3. AES的加密.解密4. DES加密/解密5. 总结 1.  摘要 C#中常用的一些加密和解密方案,如:md5加密.RSA加密与解密和DES加密等,Asp.N ...

  9. net core体系-web应用程序-4asp.net core2.0 项目实战(1)-6项目缓冲方案

    Asp.Net Core2.0下使用memcached缓存. Memcached目前微软暂未支持,暂只支持Redis,由于项目历史原因,先用博客园开源项目EnyimMemcachedCore,后续用到 ...

随机推荐

  1. css系列教程1-选择器全解

    全栈工程师开发手册 (作者:栾鹏) 一个demo学会css css系列教程1-选择器全解 css系列教程2-样式操作全解 css选择器全解: css选择器包括:基本选择器.属性选择器.伪类选择器.伪元 ...

  2. git的使用(入门篇)

    1.Git 的安装 Window 下的安装 从 http://git-scm.com/download 上下载window版的客户端,然后一直下一步下一步安装git即可,请注意,如果你不熟悉每个选项的 ...

  3. masonry 设置控件抗压缩及抗拉伸

    使用masonry正常设置约束时两个label的显示是下图 添加代码设置蓝色label的抗压缩属性后( [self.missionNameLabel setContentCompressionResi ...

  4. AspectCore.Extension.Reflection : .NET Core反射扩展库

    在从零实现AOP的过程中,难免会需要大量反射相关的操作,虽然在.net 4.5+/.net core中反射的性能有了大幅的优化,但为了追求极致性能,自己实现了部分反射的替代方案,包括构造器调用.方法调 ...

  5. 简述static关键字、void与void *(void指针)、函数指针

    static关键字1.修饰局部变量,延长局部变量的生命周期.使变量成为静态局部变量,在编译时就为变量分配内存,直到程序退出才释放存储单元.2.修饰全局变量,限制全局变量的使用范围为本文件中.全局变量默 ...

  6. 图论 Warshall 和Floyd 矩阵传递闭包

    首先我们先说下图论,一般图存储可以使用邻接矩阵,或邻接表,一般使用邻接矩阵在稠密图比较省空间. 我们来说下有向图,一般的有向图也是图,图可以分为稠密图,稀疏图,那么从意思上,稠密图就是点的边比较多,稀 ...

  7. WebService调用(基于KSOAP2)

    public static boolean getData(String param) { //WebService服务器地址 String SERVICE_URL = "http://22 ...

  8. [Bayesian] “我是bayesian我怕谁”系列 - Exact Inferences

    要整理这部分内容,一开始我是拒绝的.欣赏贝叶斯的人本就不多,这部分过后恐怕就要成为“从入门到放弃”系列. 但,这部分是基础,不管是Professor Daphne Koller,还是统计学习经典,都有 ...

  9. swift之函数式编程(三)

    文章来源于<Functional Programing in Swift>,本系列仅仅是观后概括的一些内容 Wrapping Core Image 上一篇文章我们介绍了 高阶函数并且展示了 ...

  10. 独热编码OneHotEncoder简介

    在分类和聚类运算中我们经常计算两个个体之间的距离,对于连续的数字(Numric)这一点不成问题,但是对于名词性(Norminal)的类别,计算距离很难.即使将类别与数字对应,例如{'A','B','C ...