HI 1 year ago
parent 74385bb165
commit 4dda70f07e
  1. 414
      .gitignore
  2. 14
      PEIS.Cloud/Controllers/SampleController.cs
  3. 21
      PEIS.Cloud/Program.cs
  4. 30
      PEIS.Cloud/Properties/launchSettings.json
  5. 167
      PEIS.Cloud/Startup.cs
  6. 9
      PEIS.Cloud/appsettings.Development.json
  7. 18
      PEIS.Cloud/appsettings.json
  8. 53
      PEIS.Common/Helper/Auth/AuthHelper.cs
  9. 22
      PEIS.Common/Helper/Auth/JwtHelper.cs
  10. 58
      PEIS.Common/Helper/Cache/CacheHelper.cs
  11. 71
      PEIS.Common/Helper/Code/CodeHelper.cs
  12. 27
      PEIS.Common/Helper/Encryption/AppSettingJsonHelper.cs
  13. 17
      PEIS.Common/Helper/Encryption/ConnectionStringsHelper.cs
  14. 61
      PEIS.Common/Helper/Encryption/DesHelper.cs
  15. 102
      PEIS.Common/Helper/Encryption/RsaHelper.cs
  16. 45
      PEIS.Common/Helper/Entity/ModelToEntity.cs
  17. 45
      PEIS.Common/Helper/Excel/ExcelHelper.cs
  18. 52
      PEIS.Common/Helper/File/FileHelper.cs
  19. 18
      PEIS.Common/Helper/Nlog/LogHelper.cs
  20. 97
      PEIS.Common/Helper/Page/PageHelper.cs
  21. 127
      PEIS.Common/Helper/Redis/RedisHelper.cs
  22. 112
      PEIS.Common/Helper/Request/RequestHelper.cs
  23. 365
      PEIS.Common/Helper/Response/ResponseHelper.cs
  24. 304
      PEIS.Common/Helper/SqlServer/SqlHelper.cs
  25. 34
      PEIS.Common/Helper/StringText/PinYinHelper.cs
  26. 25
      PEIS.Common/Helper/StringText/StringHelper.cs
  27. 20
      PEIS.Common/Helper/StringText/TypeChangeHelper.cs
  28. 45
      PEIS.Common/Helper/Verify/IdCardHelper.cs
  29. 24
      PEIS.Common/Helper/WeChat/Models/SubscribeMessage/AuditResult.cs
  30. 26
      PEIS.Common/Helper/WeChat/Models/SubscribeMessage/PaymentSuccessful.cs
  31. 14
      PEIS.Common/Helper/WeChat/Models/SubscribeMessageModel.cs
  32. 8
      PEIS.Common/Helper/WeChat/Models/TokenModel.cs
  33. 36
      PEIS.Common/Helper/WeChat/Models/UnlimitedQrCodeModel.cs
  34. 15
      PEIS.Common/Helper/WeChat/Models/WeChatPayModel.cs
  35. 8
      PEIS.Common/Helper/WeChat/Response/OpenIdResponse.cs
  36. 8
      PEIS.Common/Helper/WeChat/Response/UnlimitedQrCodeResponse.cs
  37. 8
      PEIS.Common/Helper/WeChat/Response/WeChatResponse.cs
  38. 77
      PEIS.Common/Helper/WeChat/WeChat.cs
  39. 131
      PEIS.Common/Middleware/JwtMiddleware.cs
  40. 30
      PEIS.Common/Nlog.config
  41. 41
      PEIS.Common/README.md
  42. 13
      PEIS.Repositories/Context/SampleContext.cs
  43. 13
      PEIS.Repositories/Dtos/SampleDto.cs
  44. 26
      PEIS.Repositories/Enums/ConfigEnum.cs
  45. 18
      PEIS.Repositories/IRepository.cs
  46. 13
      PEIS.Repositories/Models/Sample.cs
  47. 53
      PEIS.Repositories/Repository.cs
  48. 13
      PEIS.Service/Domain/SampleDomain.cs
  49. 12
      PEIS.Service/IService/ISampleService.cs
  50. 19
      PEIS.Service/Service/SampleService.cs
  51. 43
      PEIS.sln

414
.gitignore vendored

@ -1,4 +1,412 @@
*.csproj
<<<<<<< HEAD
packages/
AutoUpdate/
ConsoleApp/
DicomTool/
IDCardRead/
PublishUpgrade/
Scale/
PEIS/PEIS.zip
# ---> VisualStudio
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
bin/
obj/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# ---> SVN
.svn/

@ -1,14 +0,0 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace PEIS.Cloud.Controllers
{
/// <summary>
/// 实例接口文件 在这里写相关的接口返回,不同业务用不同文件夹区分(git不允许提交空文件夹,所以建了文件夹需要在下面新建文件)
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class SampleController : ControllerBase
{
}
}

@ -1,21 +0,0 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using NLog.Web;
namespace PEIS.Cloud
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).UseNLog().Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}

@ -1,30 +0,0 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57770",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"PEIS.Interface": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

@ -1,167 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using PEIS.Common.Helper.Encryption;
using PEIS.Common.Middleware;
namespace PEIS.Cloud
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
private readonly bool _swagger = AppSettingJsonHelper.GetSection("Swagger", "Using") == "true";
public IConfiguration Configuration { get; }
/// <summary>
/// 这个方法被运行时调用。 使用此方法向容器添加服务
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
// swagger 配置
if (_swagger)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "OutCollect", Version = "v1" });
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath, true);
//添加Authorization
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme.",
Name = "Authorization",
In = ParameterLocation.Header,
Scheme = "bearer",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT"
});
//把所有方法配置为增加bearer头部信息;
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "bearerAuth"
}
},
new string[] {}
}
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
},
new List<string>()
}
});
});
}
// jwt 配置
services.AddAuthentication(options =>
{
// 设置默认使用jwt验证方式
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
var confSection = Configuration.GetSection("Authentication");
options.TokenValidationParameters = new TokenValidationParameters()
{
// 验证接收者
ValidateAudience = true,
// 验证发布者 //是否验证发行人,就是验证载荷中的Iss是否对应ValidIssuer参数
ValidateIssuer = true,
// 验证过期时间//是否验证过期时间,过期了就拒绝访问
ValidateLifetime = true,
// 验证秘钥 //是否验证签名,不验证的画可以篡改数据,不安全
ValidateIssuerSigningKey = true,
// 读配置Issuer//发行人
ValidIssuer = confSection["IsSure"],
// 读配置Audience//订阅人
ValidAudience = confSection["Audience"],
// 设置生成token的秘钥 //解密的密钥
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(confSection["SecurityKey"]))
};
});
}
/// <summary>
/// 此方法由运行时调用。 使用此方法配置 HTTP 请求管道
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/error");
}
if (_swagger)
{
app.UseSwagger();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger(c =>
{
c.SerializeAsV2 = true;
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "debug NetFL v1");
});
}
app.UseHttpsRedirection();
app.UseRouting();
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
// jwt
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

@ -1,18 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Authentication": {
"IsSure": "OutCollect",
"Audience": "OutCollectColoud",
"SecurityKey": "4C6A8A8B-1B9F-12E7-60C4-123BC0BB5D25"
},
"Swagger": {
"Using": "true"
}
}

@ -1,53 +0,0 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace PEIS.Common.Helper.Auth
{
public class AuthHelper
{
private readonly IConfiguration _configuration;
/// <param name="configuration"></param>
public AuthHelper(IConfiguration configuration)
{
_configuration = configuration;
}
/// <summary>
/// 生成jwt的token
/// </summary>
/// <param name="userInfo"></param>
/// <returns></returns>
public string GetToken(dynamic userInfo)
{
var dynamicProperties =(PropertyInfo[]) userInfo.GetType().GetProperties();
// token中的claims用于储存自定义信息,如登录之后的用户id等
var claims = new Claim[dynamicProperties.Length];
for (var i = 0; i < dynamicProperties.Length; i++)
{
claims[i] = new Claim(dynamicProperties[i].Name, userInfo.GetType().GetProperty(dynamicProperties[i].Name).GetValue(userInfo,null)?.ToString());
}
// 获取SecurityKey
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("Authentication")["SecurityKey"]));
var token = new JwtSecurityToken(
issuer: _configuration.GetSection("Authentication")["IsSure"], // 发布者
audience: _configuration.GetSection("Authentication")["Audience"], // 接收者
notBefore: DateTime.Now, // token签发时间
expires: DateTime.Now.AddMinutes(30), // token过期时间
claims: claims, // 该token内存储的自定义字段信息
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) // 用于签发token的秘钥算法
);
// 返回成功信息,写出token
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}

@ -1,22 +0,0 @@
using System.Linq;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
namespace PEIS.Common.Helper.Auth
{
public static class JwtHelper
{
/// <summary>
/// 获取当前jwt缓存里面的数值 直接本地this.CurValue即可
/// </summary>
/// <param name="controller"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string CurValue(this ControllerBase controller,string key)
{
var auth = controller.HttpContext.AuthenticateAsync().Result.Principal.Claims;
var value = auth.FirstOrDefault(t => t.Type.Equals(key))?.Value;
return value;
}
}
}

@ -1,58 +0,0 @@
using System;
using Microsoft.Extensions.Caching.Memory;
namespace PEIS.Common.Helper.Cache
{
/// <summary>
/// 缓存框架
/// </summary>
public class CacheHelper
{
private readonly IMemoryCache _memoryCache;
/// <summary>
/// 缓存框架
/// </summary>
/// <param name="memoryCache"></param>
public CacheHelper(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
/// <summary>
/// 存缓存
/// </summary>
/// <param name="key">关键词</param>
/// <param name="value">值</param>
public void Set(string key, string value)
{
var cacheOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5));
_memoryCache.Set(key, value,cacheOptions);
}
/// <summary>
/// 存缓存 带时效
/// </summary>
/// <param name="key">关键词</param>
/// <param name="value">值</param>
/// <param name="aging">时效</param>
public void SetAging(string key, string value,int aging)
{
var cacheOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(aging));
_memoryCache.Set(key, value, cacheOptions);
}
/// <summary>
/// 获取缓存值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string Get(string key)
{
return _memoryCache.TryGetValue(key, out string value) ? value:"";
}
}
}

@ -1,71 +0,0 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using QRCoder;
namespace PEIS.Common.Helper.Code
{
public class CodeHelper
{
private static Bitmap QcCode(string text)
{
var qrGenerator = new QRCodeGenerator();
var qrCodeData = qrGenerator.CreateQrCode(text, QRCodeGenerator.ECCLevel.Q);
var qrCode = new QRCode(qrCodeData);
return qrCode.GetGraphic(20, Color.Black, Color.White, new Bitmap(Path.Combine(Directory.GetCurrentDirectory(), "Image", "Logo.jpg")));
}
private static Bitmap QcCodeTitle(string text,string title)
{
var qrCodeImage = QcCode(text);
var bitmap = new Bitmap(500, 450);
var g = Graphics.FromImage(bitmap);
var font = new Font("SimSun", 24, FontStyle.Regular);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(Color.White);
g.DrawImage(qrCodeImage, 50, 0, 400, 400);
var solidBrush = new SolidBrush(Color.Black);
g.DrawString(title, font, solidBrush, 190, 400);
g.Dispose();
qrCodeImage.Dispose();
return bitmap;
}
/// <summary>
/// 获取二维码
/// </summary>
/// <param name="text">文本</param>
/// <param name="title"></param>
/// <param name="filePath">生成文件地址</param>
public static void QcCodeForFilePath(string text, string title, string filePath)
{
var map = QcCodeTitle(text,title);
map.Save(filePath + title, ImageFormat.Png);
map.Dispose();
}
/// <summary>
/// 获取带标题的二维码
/// </summary>
/// <param name="text"></param>
/// <param name="title"></param>
/// <returns></returns>
public static string QcCodeBase64(string text,string title)
{
using var ms = new MemoryStream();
var map = QcCodeTitle(text,title);
map.Save(ms, ImageFormat.Png);
map.Dispose();
return Convert.ToBase64String(ms.GetBuffer());
}
}
}

@ -1,27 +0,0 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
namespace PEIS.Common.Helper.Encryption
{
/// <summary>
/// 获取配置文件信息
/// </summary>
public class AppSettingJsonHelper
{
private static readonly IConfiguration Configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
/// <summary>
/// 获取配置文件里面的参数
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetSection(string section,string key)
{
return Configuration.GetSection(section)[key];
}
}
}

@ -1,17 +0,0 @@
namespace PEIS.Common.Helper.Encryption
{
public class ConnectionStringsHelper
{
/// <summary>
/// 直接返回解密后的connectionString
/// </summary>
/// <param name="configName"></param>
/// <param name="configValue"></param>
/// <returns></returns>
public static string GetDesConfig(string configName,string configValue)
{
return DesHelper.DesDecrypt(AppSettingJsonHelper.GetSection(configName, configValue));
}
}
}

@ -1,61 +0,0 @@
using System;
using System.IO;
using System.Security.Cryptography;
namespace PEIS.Common.Helper.Encryption
{
public class DesHelper
{
private const string Key = "Blue2021";
private const string Iv = "Flag2021";
/// <summary>
/// DES加密
/// </summary>
/// <param name="data">加密数据</param>
/// <returns></returns>
public static string DesEncrypt(string data)
{
var byKey = System.Text.Encoding.ASCII.GetBytes(Key);
var byIv = System.Text.Encoding.ASCII.GetBytes(Iv);
var cryptoProvider = new DESCryptoServiceProvider();
var ms = new MemoryStream();
var cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIv), CryptoStreamMode.Write);
var sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="data">解密数据</param>
/// <returns></returns>
public static string DesDecrypt(string data)
{
var byKey = System.Text.Encoding.ASCII.GetBytes(Key);
var byIv = System.Text.Encoding.ASCII.GetBytes(Iv);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
var cryptoProvider = new DESCryptoServiceProvider();
var ms = new MemoryStream(byEnc);
var cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIv), CryptoStreamMode.Read);
var sr = new StreamReader(cst);
return sr.ReadToEnd();
}
}
}

@ -1,102 +0,0 @@
using System;
using System.Security.Cryptography;
namespace PEIS.Common.Helper.Encryption
{
public class RsaHelper
{
private RSACryptoServiceProvider Csp { get; set; }
private RSAParameters PrivateKey { get; set; }
private RSAParameters PublicKey { get; set; }
/// <summary>
/// 公钥字符串
/// </summary>
public string PublicKeyString { get; set; }
private RsaHelper()
{
Csp = new RSACryptoServiceProvider(2048);
//how to get the private key
PrivateKey = Csp.ExportParameters(true);
//and the public key ...
PublicKey = Csp.ExportParameters(false);
//converting the public key into a string representation
{
//we need some buffer
var sw = new System.IO.StringWriter();
//we need a serializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//serialize the key into the stream
xs.Serialize(sw, PublicKey);
//get the string from the stream
PublicKeyString = sw.ToString();
}
//converting it back
{
//get a stream from the string
var sr = new System.IO.StringReader(PublicKeyString);
//we need a deserializer
var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
//get the object back from the stream
PublicKey = (RSAParameters)xs.Deserialize(sr);
}
}
static RsaHelper(){}
public static RsaHelper Instance { get; } = new RsaHelper();
/// <summary>
/// 加密数据
/// </summary>
/// <param name="keyWord"></param>
/// <returns></returns>
public string DesEncrypt(string keyWord)
{
//lets take a new CSP with a new 2048 bit rsa key pair
//conversion for the private key is no black magic either ... omitted
//we have a public key ... let's get a new csp and load that key
Csp = new RSACryptoServiceProvider();
Csp.ImportParameters(PublicKey);
//for encryption, always handle bytes...
var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(keyWord);
//apply pkcs#1.5 padding and encrypt our data
var bytesCypherText = Csp.Encrypt(bytesPlainTextData, false);
//we might want a string representation of our cypher text... base64 will do
return Convert.ToBase64String(bytesCypherText);
}
/// <summary>
/// 解密数据
/// </summary>
/// <param name="keyWord"></param>
/// <returns></returns>
public string DesDecrypt(string keyWord)
{
//first, get our bytes back from the base64 string ...
var bytesCypherText = Convert.FromBase64String(keyWord);
//we want to decrypt, therefore we need a csp and load our private key
var csp = new RSACryptoServiceProvider();
csp.ImportParameters(PrivateKey);
//decrypt and strip pkcs#1.5 padding
var bytesPlainTextData = csp.Decrypt(bytesCypherText, false);
//get our original plainText back...
return System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
}
}
}

@ -1,45 +0,0 @@
using System;
namespace PEIS.Common.Helper.Entity
{
public class ModelToEntity<TM,TE>
{
/// <summary>
/// 类型转换,有则赋值,没有则默认值 这个可以不传需要转换的值
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static TE Change(TM model)
{
var modelPropertyInfos = typeof(TM).GetProperties();
var entityType = typeof(TE);
var entity =(TE)Activator.CreateInstance(typeof(TE));
foreach (var modelPropertyInfo in modelPropertyInfos)
{
if(entityType.GetProperty(modelPropertyInfo.Name)!=null)
entityType.GetProperty(modelPropertyInfo.Name)?.SetValue(entity, modelPropertyInfo.GetValue(model), null);
}
return entity;
}
/// <summary>
/// 类型转换,只是这个可以传入需要转换的值
/// </summary>
/// <param name="model"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static TE Set(TM model,TE entity)
{
var modelPropertyInfos = typeof(TM).GetProperties();
var entityType = typeof(TE);
foreach (var modelPropertyInfo in modelPropertyInfos)
{
if (entityType.GetProperty(modelPropertyInfo.Name) != null)
entityType.GetProperty(modelPropertyInfo.Name)?.SetValue(entity, modelPropertyInfo.GetValue(model), null);
}
return entity;
}
}
}

@ -1,45 +0,0 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ExcelDataReader;
namespace PEIS.Common.Helper.Excel
{
public class ExcelHelper
{
static ExcelHelper() { }
private ExcelHelper() { }
public static ExcelHelper Instance { get; } = new ExcelHelper();
/// <summary>
/// 读取excel的帮助类 必须传该excel有几列
/// </summary>
/// <param name="filePath"></param>
/// <param name="columnCount"></param>
/// <returns></returns>
public List<List<string>> Read(string filePath,int columnCount)
{
var excelContent = new List<List<string>>();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
using var stream = System.IO.File.Open(filePath, FileMode.Open, FileAccess.Read);
using var reader = ExcelReaderFactory.CreateReader(stream);
do
{
while (reader.Read())
{
var cellContent = new List<string>();
for (var i = 0; i < columnCount; i++)
{
cellContent.Add(reader[i]==null?"": reader[i].ToString());
}
if(!cellContent.All(string.IsNullOrEmpty))
excelContent.Add(cellContent);
}
} while (reader.NextResult());
return excelContent;
}
}
}

@ -1,52 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using PEIS.Common.Helper.Nlog;
namespace PEIS.Common.Helper.File
{
public class FileHelper
{
/// <summary>
/// 创建文件夹
/// </summary>
/// <param name="file"></param>
public static void CreateFile(string file)
{
if (Directory.Exists(file))
//文件夹已经存在
return;
try
{
Directory.CreateDirectory(file);
//创建成功
}
catch (Exception e)
{
LogHelper.Log.Error($"文件创建出错:{e.ToString()}");
}
}
/// <summary>
/// 获取文件大小
/// </summary>
/// <param name="length">文件长度</param>
/// <returns></returns>
public static string FileSize(long length)
{
var unit = new List<string>() { "K", "M", "G" };
var size = Math.Round(length / 1024.0, 2);
var index = 0;
while (size > 1024 && index < 2)
{
index++;
size = Math.Round(size / 1024, 2);
}
return $"{size}{unit[index]}";
}
}
}

@ -1,18 +0,0 @@
using NLog;
namespace PEIS.Common.Helper.Nlog
{
/// <summary>
/// 日志静态类
/// </summary>
public class LogHelper
{
/// <summary>
/// 日志调用对象
/// </summary>
public static readonly NLog.Logger Log = LogManager.GetCurrentClassLogger();
}
}

@ -1,97 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace PEIS.Common.Helper.Page
{
/// <summary>
/// 分页帮助类
/// </summary>
public class PageHelper
{
/*
* 1. list.Skip(x).Take(y);
* 2.(x,y)(0,list.Count)list为空[],()
*/
/// <summary>
/// 分页
/// </summary>
/// <typeparam name="T">数据类型</typeparam>
/// <param name="list">数据</param>
/// <param name="page">页码</param>
/// <param name="size">数据量/页</param>
/// <returns></returns>
public static Data Pagination<T>(List<T> list, int page, int size)
{
if (list == null)
return new Data(0, page, null);
if (list.Count != 0 && list.Count >= size)
return new Data(list.Count, page <= 0 ? 0 : page,
list.Skip(Convert.ToInt32((page <= 0 ? 0 : page - 1) * size)).Take(size).ToList());
return new Data(list.Count, page, list);
}
/// <summary>
/// 该分页方法适用于sql server 2008 .net core 3.1不支持2008数据库
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="db"></param>
/// <param name="dbTable"></param>
/// <param name="page"></param>
/// <param name="size"></param>
/// <returns></returns>
public static Data Pagination<T>(DbContext db, DbSet<T> dbTable, int page, int size) where T : class
{
var entityType = db.Model.FindEntityType(typeof(T));
var tableName = entityType.GetTableName();
var primaryKeyName = entityType.FindPrimaryKey().Properties.First().Name;
return new Data(dbTable.Count(), page, dbTable.FromSqlRaw($"select * from (select ROW_NUMBER() OVER(ORDER BY {primaryKeyName}) RowSerialNumber ,* from {tableName}) s where RowSerialNumber BETWEEN {(page - 1) * size + 1} and {page * size}").ToList());
}
/// <summary>
/// 该方法适用于sql server 2008以上的数据库 sql server 2008会报错
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="page"></param>
/// <param name="size"></param>
/// <returns></returns>
public static Data Pagination<T>(IEnumerable<T> list, int page, int size)
{
return list == null ? new Data(0, page, null) : new Data(list.Count(), page, list.Skip(Convert.ToInt32((page <= 0 ? 0 : page - 1) * size)).Take(size).ToList());
}
}
/// <summary>
/// 数据页数
/// </summary>
public class Data
{
/// <summary>
/// 总数
/// </summary>
public int? Total { get; set; }
/// <summary>
/// 当前页码
/// </summary>
public int? Current { get; set; }
/// <summary>
/// 数据
/// </summary>
public object List { get; set; }
/// <summary>
/// 入参
/// </summary>
/// <param name="total"></param>
/// <param name="current"></param>
/// <param name="list"></param>
public Data(int? total, int? current, object list)
{
Total = total ?? 0;
Current = current;
List = list;
}
}
}

@ -1,127 +0,0 @@
using System;
using Newtonsoft.Json;
using PEIS.Common.Helper.Encryption;
using StackExchange.Redis;
namespace PEIS.Common.Helper.Redis
{
/// <summary>
/// Redis帮助类--- 项目的appsetting.json 文件里面必须包含 Redis ConnectionString 的配置
/// </summary>
public class RedisHelper
{
private static readonly object Locker = new object();
//连接多路复用器
private ConnectionMultiplexer _redisMultiplexer;
private IDatabase _db = null;
private static RedisHelper _instance = null;
/// <summary>
/// 单例模式
/// </summary>
public static RedisHelper Instance
{
get
{
if (_instance != null) return _instance;
lock (Locker)
{
_instance ??= new RedisHelper();
}
return _instance;
}
}
/// <summary>
/// 连接redis
/// </summary>
public void InitConnect()
{
try
{
//连接redis服务器
var redisConnection = AppSettingJsonHelper.GetSection("Redis","ConnectionString");
_redisMultiplexer = ConnectionMultiplexer.Connect(redisConnection);
_db = _redisMultiplexer.GetDatabase();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
_redisMultiplexer = null;
_db = null;
}
}
/// <summary>
/// 实例化
/// </summary>
public RedisHelper()
{
InitConnect();
}
#region 通用key操作
/// <summary>
/// 判断键是否存在
/// </summary>
public bool ExistsKey(string key)
{
return _db.KeyExists(key);
}
/// <summary>
/// 删除键
/// </summary>
public bool DeleteKey(string key)
{
return _db.KeyDelete(key);
}
#endregion
#region string操作
/// <summary>
/// 保存单个key value
/// </summary>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <param name="expiry">过期时间</param>
public bool SetStringKey(string key, string value, TimeSpan? expiry=null)
{
expiry ??= new TimeSpan(0, 5, 0);
return _db.StringSet(key, value, expiry);
}
/// <summary>
/// 获取单个key的值
/// </summary>
public RedisValue GetRedisValue(string key)
{
return _db.StringGet(key);
}
public string GetStringValue(string key)
{
return _db.StringGet(key);
}
/// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T">对象的类型</typeparam>
public bool SetObjectKey<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
var json = JsonConvert.SerializeObject(obj);
return _db.StringSet(key, json, expiry);
}
/// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
public T GetStringKey<T>(string key)
{
var value = _db.StringGet(key);
return value.IsNullOrEmpty ? default : JsonConvert.DeserializeObject<T>(value);
}
#endregion
}
}

@ -1,112 +0,0 @@
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace PEIS.Common.Helper.Request
{
public class RequestHelper
{
/// <summary>
/// get方法获取文件流
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static async Task<Stream> GetFileStream(string url)
{
using var client = new HttpClient();
var msg = await client.GetAsync($"{url}");
if (!msg.IsSuccessStatusCode) return null;
// create a new file to write to
var contentStream = await msg.Content.ReadAsStreamAsync();
return contentStream;
}
/// <summary>
/// get方法返回实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <returns></returns>
public static async Task<T> GetEntity<T>(string url)
{
using var client = new HttpClient();
var msg = await client.GetAsync($"{url}");
if (!msg.IsSuccessStatusCode) return default;
var content = await msg.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(content);
}
/// <summary>
/// get方法返回文本字符
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static async Task<string> GetString(string url)
{
using var client = new HttpClient();
var msg = await client.GetAsync($"{url}");
if (!msg.IsSuccessStatusCode) return default;
return await msg.Content.ReadAsStringAsync();
}
/// <summary>
/// post方法返回文件流
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static async Task<Stream> PostFileStream<T>(string url,T entity)
{
using var client = new HttpClient();
var msg = await client.PostAsync($"{url}", new StringContent(JsonConvert.SerializeObject(entity), Encoding.UTF8, "application/json"));
if (!msg.IsSuccessStatusCode) return null;
// create a new file to write to
var contentStream = await msg.Content.ReadAsStreamAsync(); // get the actual content stream
return contentStream;
}
/// <summary>
/// post方法返回实体对象
/// </summary>
/// <typeparam name="TR"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static async Task<TR> PostEntity<TR,T>(string url,T entity)
{
using var client = new HttpClient();
var msg = await client.PostAsync($"{url}", new StringContent(JsonConvert.SerializeObject(entity), Encoding.UTF8, "application/json"));
if (!msg.IsSuccessStatusCode) return default;
var content = await msg.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TR>(content);
}
public static async Task<TR> PostFormDataEntity<TR>(string url, FormUrlEncodedContent formUrl)
{
using var client = new HttpClient();
var msg = await client.PostAsync($"{url}", formUrl);
if (!msg.IsSuccessStatusCode) return default;
var content = await msg.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TR>(content);
}
/// <summary>
/// post方法返回文本字符
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="entity"></param>
/// <returns></returns>
public static async Task<string> PostString<T>(string url,T entity)
{
using var client = new HttpClient();
var msg = await client.PostAsync($"{url}", new StringContent(JsonConvert.SerializeObject(entity), Encoding.UTF8, "application/json"));
if (!msg.IsSuccessStatusCode) return default;
return await msg.Content.ReadAsStringAsync();
}
}
}

@ -1,365 +0,0 @@
using System;
using System.ComponentModel;
using Microsoft.AspNetCore.Mvc;
namespace PEIS.Common.Helper.Response
{
public static class ResponseHelper
{
/// <summary>
/// 首位:
/// 3:warning
/// 4:info(提示信息)
/// 5:error;
/// 6:后端校验,前端不报错
/// 倒数第二位:
/// 0:代码校验出的错
/// 1:业务流程里面的错误
/// 4: notFind
/// 5: 权限
/// </summary>
public enum ErrorEnum
{
#region 3:warning
//倒数第二位 0
//倒数第二位 1
/// <summary>
/// 申请单已经发送到检验科,请联系检验科取消配血,并在his中删除医嘱及记账信息
/// </summary>
[Description("申请单已经发送到检验科,请联系检验科取消配血,并在his中删除医嘱及记账信息")]
HasBeenSent = 30011,
/// <summary>
/// 申请已发送或已作废,请勿重复操作
/// </summary>
[Description("申请已发送或已作废,请勿重复操作")]
RepeatSending = 30012,
/// <summary>
/// 条码作废- 改条码在检验科已经扫码上机,不能作废
/// </summary>
[Description("该条码在检验科已经扫码上机,不能作废")]
NotCancelBarcode = 30013,
/// <summary>
/// 检验科未发血
/// </summary>
[Description("检验科未发血")]
NotSend = 30014,
/// <summary>
/// 血袋已接收
/// </summary>
[Description("血袋已接收")]
BloodReceived = 30015,
/// <summary>
/// 操作时间不能超过当前时间
/// </summary>
[Description("操作时间不能超过当前时间")]
NurseTimeOut = 30016,
/// <summary>
/// 输注记录已反馈
/// </summary>
[Description("输注记录已反馈")]
InfusionFeedback = 3017,
/// <summary>
/// 输注记录已反馈
/// </summary>
[Description("血袋配血科室不匹配")]
DeptMismatch = 3018,
[Description("自助申请单名称重复")]
ApplicationNameRepeat = 30019,
[Description("该用户码不属于此次采集场所")]
UserCodeError = 300101,
[Description("该申请未审核")]
ApplicationNotAudit = 300102,
[Description("Excel有误")]
ExcelIsError = 300103,
[Description("未付款")]
Unpaid = 300104,
[Description("该用户信息已经注册过")]
UserInfoRepeat = 300105,
[Description("该用户信息已经注册过")]
UserBindRepeat = 300106,
[Description("已超过最终上传时间")]
UploadFileTimeOut = 300107,
[Description("请登录")]
NotLogin = 300108,
[Description("团检申请不能停用")]
GroupInspectionNotDelete = 300109,
[Description("该申请已经停用")]
ApplicationIsStop = 300120,
//倒数第二位 4
/// <summary>
/// 未找到数据
/// </summary>
[Description("未找到数据")]
NotFindData = 30041,
/// <summary>
/// 未找到输血申请单信息
/// </summary>
[Description("未找到输血申请单信息")]
NotFindBloodRequest = 30042,
/// <summary>
/// 未找到患者信息
/// </summary>
[Description("未找到患者信息")]
NotFindPatientInfo = 30043,
/// <summary>
/// 未找到样本信息
/// </summary>
[Description("未找到样本信息")]
NotFindSampleInfo = 30044,
/// <summary>
/// 未找到知情同意书信息
/// </summary>
[Description("未找到知情同意书信息")]
NotFindInformed = 30045,
/// <summary>
/// 未找到交叉配血信息
/// </summary>
[Description("未找到交叉配血信息")]
NotFindBloodMatch = 30046,
/// <summary>
/// 未找到血袋库存信息
/// </summary>
[Description("未找到血袋库存信息")]
NotFindBlood = 30047,
/// <summary>
/// 未找到输注记录数据
/// </summary>
[Description("未找到输注记录")]
NotFindInfusion = 30048,
/// <summary>
/// 未找到不良反应记录
/// </summary>
[Description("未找到不良反应记录")]
NotFindReaction = 30049,
/// <summary>
/// 未找到输注前巡视记录
/// </summary>
[Description("未找到输注前巡视记录")]
NotFindBeforeInspect = 30410,
/// <summary>
/// 未找到报告单
/// </summary>
[Description("未找到报告单")]
NotFindReport = 30411,
//倒数第二位 5 权限
/// <summary>
/// 输血申请未审核
/// </summary>
[Description("输血申请未审核")]
UnReviewBloodRequisition = 30051,
/// <summary>
/// 未进行医生审核
/// </summary>
[Description("未进行医生审核")]
UnReviewDoctor = 30052,
/// <summary>
/// 权限不足,医生无相关证书信息,如果确有证书请到his添加
/// </summary>
[Description("权限不足,医生无相关证书信息,如果确有证书请到his添加")]
InsufficientPermissions = 30053,
/// <summary>
/// 医生审核职称权限不足
/// </summary>
[Description("权限不足,医生职称不符合审核要求")]
InsufficientDoctorTitle = 30054,
/// <summary>
/// 护士审核权限不足
/// </summary>
[Description("护士审核权限不足")]
NurseInsufficient = 30055,
#endregion
#region 4:info
/// <summary>
/// 正在配血,请等待
/// </summary>
[Description("正在配血,请等待")]
Matching = 40011,
#endregion
#region 5:error
/// <summary>
/// Token错误
/// </summary>
[Description("Token错误")]
TokenError = 50001,
[Description("参数错误")]
ParamsError = 50002,
[Description("登录失败,用户名或密码错误")]
UserAndPwError = 50011,
/// <summary>
/// 医嘱业务流程错误-输血申请单发送
/// </summary>
[Description("业务逻辑错误")]
BusinessError = 50012,
/// <summary>
/// 血型未确认-创建知情同意书
/// </summary>
[Description("患者血型未确认")]
BloodAboRhError = 50013,
/// <summary>
/// 科室不匹配-首页获取在院患者列表
/// </summary>
[Description("科室不匹配")]
DeptMismatchError = 50014,
#endregion
#region 6:后端校验,前端不报错
[Description("登录失败,用户名或密码为空")]
UserAndPwIsNull = 60001,
#endregion
}
/// <summary>
/// 获取枚举对应的Description
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
public static string GetDescription(this Enum val)
{
var field = val.GetType().GetField(val.ToString());
if (field == null)
return null;
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
return customAttribute == null ? val.ToString() : ((DescriptionAttribute)customAttribute).Description;
}
/// <summary>
/// 返回需单独处理错误的信息
/// </summary>
/// <param name="enums"></param>
/// <returns></returns>
public static ActionResult Fail(ErrorEnum enums)
{
var code = Convert.ToInt32(enums);
var message = enums.GetDescription();
var result = new ResultModel(code, message, "");
return new OkObjectResult(result);
}
/// <summary>
/// 返回需单独处理错误的信息,自定义message
/// </summary>
/// <param name="enums"></param>
/// <param name="message"></param>
/// <returns></returns>
public static ActionResult Fail(ErrorEnum enums, string message)
{
var code = Convert.ToInt32(enums);
var result = new ResultModel(code, message, "");
return new OkObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="enums"></param>
/// <returns></returns>
public static ActionResult Fail(object data, ErrorEnum enums)
{
var result = new ResultModel(Convert.ToInt32(enums),enums.GetDescription(), data);
return new OkObjectResult(result);
}
/// <summary>
/// 成功(200,无返回)
/// </summary>
/// <returns></returns>
public static ActionResult Success()
{
var result = new ResultModel(200, "Success", "");
return new OkObjectResult(result);
}
/// <summary>
/// 成功(200,返回数据)
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static ActionResult Success(object data)//File(ms.ToArray(), "application/pdf");
{
var result = new ResultModel(200, "Success", data);
return new OkObjectResult(result);
}
/// <summary>
/// 返回自定义错误
/// </summary>
/// <param name="message"></param>
/// <param name="code"></param>
/// <returns></returns>
public static ActionResult CustomizeFail(string message, int code = 5)
{
code = code switch
{
5 => 50001,
6 => 60001,
4 => 40001,
3 => 30001,
_ => code
};
return new OkObjectResult(new ResultModel(code, message, ""));
}
/// <summary>
/// 失败(500)
/// </summary>
/// <returns></returns>
public static ActionResult ServerError()
{
var result = new ResultModel(500, "服务器内部错误,请联系系统管理员。", "");
return new OkObjectResult(result);
}
/// <summary>
/// 失败(500)
/// </summary>
/// <returns></returns>
public static ActionResult Fail(Exception ex)
{
var result = new ResultModel(500, ex.Message, "");
return new OkObjectResult(result);
}
}
public class ResultModel
{
public int Code { get; set; }
public string Message { get; set; }
public object Data { get; set; }
public ResultModel()
{
}
public ResultModel(int code, string message, object data)
{
Code = code;
Message = message;
Data = data;
}
}
}

@ -1,304 +0,0 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Dynamic;
using System.Linq;
namespace PEIS.Common.Helper.SqlServer
{
public class SqlHelper
{
public static readonly string ConnectString = "";
private SqlConnection _con;
private SqlCommand _cmd;
private SqlDataAdapter _sda;
private SqlDataReader _sdr;
private DataSet _ds;
private DataView _dv;
public static SqlConnection GetConnection()//定义成静态的,很重要!
{
return new SqlConnection(ConnectString);
}
/// <summary>
/// 打开数据库连接
/// </summary>
public void OpenDataBase()
{
_con = new SqlConnection(ConnectString);
_con.Open();
}
/// <summary>
/// 关闭数据库连接
/// </summary>
public void CloseDataBase()
{
_con.Close();
_con.Dispose();
}
/// <summary>
/// 返回DataSet数据集
/// </summary>
/// <param name="sqlStr">数据库查询字符串</param>
/// <param name="tableName"></param>
/// <returns>DataSet</returns>
public DataSet GetDs(string sqlStr, string tableName)
{
OpenDataBase();
_sda = new SqlDataAdapter(sqlStr, _con);
_ds = new DataSet();
_sda.Fill(_ds, tableName);
CloseDataBase();
return _ds;
}
public DataView GetDv(string sqlStr)
{
OpenDataBase();
_sda = new SqlDataAdapter(sqlStr, _con);
_ds = new DataSet();
_sda.Fill(_ds);
_dv = _ds.Tables[0].DefaultView;
CloseDataBase();
return _dv;
}
/// <summary>
/// 返回DataReader对象
/// </summary>
/// <param name="sqlString">查询字符串</param>
/// <returns>返回值</returns>
public SqlDataReader GetDataReader(string sqlString)
{
OpenDataBase();
_cmd = new SqlCommand(sqlString, _con);
_sdr = _cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
return _sdr;
}
public DataSet DataSet(string sql)
{
SqlConnection con = new SqlConnection(ConnectString);
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = null;
try
{
con.Open();
ds = new DataSet();
da.Fill(ds);
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
return ds;
}
public static DataTable DataTable(string sql)
{
var con = new SqlConnection(ConnectString);
var cmd = new SqlCommand(sql, con);
var da = new SqlDataAdapter(cmd);
DataTable ds = null;
try
{
con.Open();
ds = new DataTable();
da.Fill(ds);
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
return ds;
}
public static DataTable DataTable(string sql,string connectString)
{
var con = new SqlConnection(connectString);
var cmd = new SqlCommand(sql, con);
var da = new SqlDataAdapter(cmd);
DataTable ds = null;
try
{
con.Open();
ds = new DataTable();
da.Fill(ds);
}
catch (SqlException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
return ds;
}
/// <summary>
/// 可以传入连接字符串 返回T类型对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="connectString"></param>
/// <returns></returns>
public static List<T> Entity<T>(string sql,string connectString)
{
return ConvertDataTableToEntity<T>(DataTable(sql,connectString));
}
/// <summary>
/// 根据sql语句返回 T 类型对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <returns></returns>
public static List<T> Entity<T>(string sql)
{
return ConvertDataTableToEntity<T>(DataTable(sql));
}
/// <summary>
/// 根据sql语句直接返回泛型对象
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static List<ExpandoObject> Entity(string sql)
{
return ConvertDataTableToEntity(DataTable(sql));
}
/// <summary>
/// 执行Sql语句方法没有返回值
/// </summary>
/// <param name="sqlStr">传入的查询参数</param>
public void RunSql(string sqlStr)
{
OpenDataBase();
_cmd = new SqlCommand(sqlStr, _con);
_cmd.ExecuteNonQuery();
CloseDataBase();
}
/// <summary>
/// 返回查询结果的首行首列
/// </summary>
/// <param name="sqlStr">查询字符串</param>
/// <returns>返回结果</returns>
public string ReturnSql(string sqlStr)
{
OpenDataBase();
string returnSql;
try
{
_cmd = new SqlCommand(sqlStr, _con);
returnSql = _cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
throw ex;
}
CloseDataBase();
return returnSql;
}
/// <summary>
/// 将DataTable转成 T 实体对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> ConvertDataTableToEntity<T>(DataTable dt)
{
return (from DataRow row in dt.Rows select GetItem<T>(row)).ToList();
}
/// <summary>
/// 组装实体的方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <returns></returns>
private static T GetItem<T>(DataRow dr)
{
var temp = typeof(T);
var obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (var pro in temp.GetProperties())
{
if (string.Equals(pro.Name, column.ColumnName.Replace("_", string.Empty), StringComparison.CurrentCultureIgnoreCase))
{
if (dr[column.ColumnName] is DBNull)
{
pro.SetValue(obj, default, null);
continue;
}
pro.SetValue(obj, dr[column.ColumnName], null);
if (dr[column.ColumnName] is string)
pro.SetValue(obj, Convert.ToString(dr[column.ColumnName]).Trim(), null);
}
else
continue;
}
}
return obj;
}
/// <summary>
/// 将DataTable转成 泛型实体对象
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<ExpandoObject> ConvertDataTableToEntity(DataTable dt)
{
return (from DataRow row in dt.Rows select GetItem(row)).ToList();
}
/// <summary>
/// 不需要定义实体,直接返回泛型实体
/// </summary>
/// <param name="dr"></param>
/// <returns></returns>
public static ExpandoObject GetItem(DataRow dr)
{
dynamic dynamicEntity = new ExpandoObject();
foreach (DataColumn column in dr.Table.Columns)
{
(dynamicEntity as IDictionary<string, object>).Add(column.ColumnName, (dr[column.ColumnName] is string)? dr[column.ColumnName].ToString().Trim(): dr[column.ColumnName]);
}
return dynamicEntity;
}
}
}

@ -1,34 +0,0 @@
using Microsoft.International.Converters.PinYinConverter;
namespace PEIS.Common.Helper.StringText
{
/// <summary>
/// 拼音帮助类
/// </summary>
public class PinYinHelper
{
/// <summary>
/// 获取首字母
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetFirstPinyin(string str)
{
var r = string.Empty;
foreach (var obj in str)
{
try
{
var chineseChar = new ChineseChar(obj);
var t = chineseChar.Pinyins[0];
r += t[..1];
}
catch
{
r += obj.ToString();
}
}
return r;
}
}
}

@ -1,25 +0,0 @@
using System;
namespace PEIS.Common.Helper.StringText
{
/// <summary>
/// 相关码的生成
/// </summary>
public class StringHelper
{
/// <summary>
///获取文本数字码
/// </summary>
/// <param name="code">需要转换的文本</param>
/// <param name="length">需要码长度</param>
/// <returns></returns>
public string GetCode(string code, int length)
{
code = PinYinHelper.GetFirstPinyin(code);
var random = new Random();
var numberLength = length - code.Length;
code += random.Next(Convert.ToInt32(Math.Pow(10, numberLength)),Convert.ToInt32(Math.Pow(10, numberLength + 1)));
return code;
}
}
}

@ -1,20 +0,0 @@
using System;
using System.IO;
namespace PEIS.Common.Helper.StringText
{
public class TypeChangeHelper
{
/// <summary>
/// 流转base64 适用于图片流
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static string StreamToBase64(Stream stream)
{
using var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
return Convert.ToBase64String(memoryStream.ToArray());
}
}
}

@ -1,45 +0,0 @@
using System;
namespace PEIS.Common.Helper.Verify
{
public class IdCardHelper
{
/// <summary>
/// 18位身份证验证 //校验码验证 符合GB11643-1999标准
/// </summary>
/// <param name="id">身份证号</param>
/// <returns></returns>
public static bool CheckIdCard18(string id)
{
if (long.TryParse(id.Remove(17), out var n) == false || n < Math.Pow(10, 16) ||
long.TryParse(id.Replace('x', '0').Replace('X', '0'), out n) == false)
{
return false; //数字验证
}
const string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(id.Remove(2), StringComparison.Ordinal) == -1)
{
return false; //省份验证
}
var birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
if (DateTime.TryParse(birth, out _) == false)
{
return false; //生日验证
}
var arrVerifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
var wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
var ai = id.Remove(17).ToCharArray();
var sum = 0;
for (var i = 0; i < 17; i++)
{
sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
}
Math.DivRem(sum, 11, out var y);
return arrVerifyCode[y] == id.Substring(17, 1).ToLower();
}
}
}

@ -1,24 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Models.SubscribeMessage
{
public class AuditResult
{
/// <summary>
/// 申请类型
/// </summary>
public string phrase1 { get; set; }
/// <summary>
/// 审核结果
/// </summary>
public string phrase2 { get; set; }
/// <summary>
/// 审核时间
/// </summary>
public string date3 { get; set; }
/// <summary>
/// 备注
/// </summary>
public string thing4 { get; set; }
}
}

@ -1,26 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Models.SubscribeMessage
{
public class PaymentSuccessful
{
/// <summary>
/// 就诊人
/// </summary>
public string thing6 { get; set; }
/// <summary>
/// 服务名称
/// </summary>
public string phrase1 { get; set; }
/// <summary>
/// 订单总价
/// </summary>
public string amount3 { get; set; }
/// <summary>
/// 下单时间
/// </summary>
public string date4 { get; set; }
/// <summary>
/// 备注
/// </summary>
public string thing5 { get; set; }
}
}

@ -1,14 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Models
{
public class SubscribeMessageModel
{
public string touser { get; set; }
public string template_id { get; set; }
public string page { get; set; }
public object data { get; set; }
public string miniprogram_state { get; set; }
public string lang { get; set; }
}
}

@ -1,8 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Models
{
public class TokenModel
{
public string access_token { get; set; }
public int? expires_in { get; set; }
}
}

@ -1,36 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Models
{
public class UnlimitedQrCodeModel
{
/// <summary>
/// 传参
/// </summary>
public string scene { get; set; }
/// <summary>
/// 小程序页面
/// </summary>
public string page { get; set; }
/// <summary>
/// 是否检查页面存在
/// </summary>
public bool check_path { get; set; }
/// <summary>
/// 打开版本
/// </summary>
public string env_version { get; set; }
/// <summary>
/// 宽度
/// </summary>
public int width { get; set; }
/// <summary>
/// 自动配置线条颜色
/// </summary>
public bool auto_color { get; set; }
/// <summary>
/// 是否需要透明底色
/// </summary>
public bool is_hyaline { get; set; }
}
}

@ -1,15 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Models
{
public class WeChatPayModel
{
public string PayCode { get; set; }
public string Title { get; set; }
public string CallNo { get; set; }
public decimal TotalFee { get; set; }
public string Name { get; set; }
public string CardNo { get; set; }
public string PatientId { get; set; }
public string Mid { get; set; }
public string CollectId { get; set; }
}
}

@ -1,8 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Response
{
public class OpenIdResponse : WeChatResponse
{
public string Session_Key { get; set; }
public string Openid { get; set; }
}
}

@ -1,8 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Response
{
public class UnlimitedQrCodeResponse:WeChatResponse
{
public string ContentType { get; set; }
public byte Buffer { get; set; }
}
}

@ -1,8 +0,0 @@
namespace PEIS.Common.Helper.WeChat.Response
{
public class WeChatResponse
{
public int ErrCode { get; set; }
public string ErrMsg { get; set; }
}
}

@ -1,77 +0,0 @@
using System.IO;
using System.Net.Http;
using PEIS.Common.Helper.Request;
using PEIS.Common.Helper.Response;
using PEIS.Common.Helper.WeChat.Models;
using PEIS.Common.Helper.WeChat.Response;
namespace PEIS.Common.Helper.WeChat
{
public class WeChat
{
/// <summary>
/// 小程序通过code获取openId
/// </summary>
/// <param name="appId"></param>
/// <param name="secret"></param>
/// <param name="code"></param>
/// <returns></returns>
public static string GetOpenId(string appId, string secret, string code)
{
var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}&js_code={code}&grant_type=authorization_code";
return RequestHelper.GetString(url).Result;
// var client = new HttpClient();
// var response = await client.GetAsync(uri);
// response.EnsureSuccessStatusCode();
// return await response.Content.ReadAsStringAsync();
}
/// <summary>
/// 获取token
/// </summary>
/// <param name="appId"></param>
/// <param name="secret"></param>
/// <returns></returns>
public static TokenModel GetToken(string appId, string secret)
{
var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={secret}";
return RequestHelper.GetEntity<TokenModel>(url).Result;
}
/// <summary>
/// 微信支付码
/// </summary>
/// <param name="httpIp"></param>
/// <param name="weChatPay"></param>
/// <returns></returns>
public static string QrCodePay(string httpIp,FormUrlEncodedContent weChatPay)
{
return RequestHelper.PostFormDataEntity<ResultModel>($"{httpIp}/wx/pay/qrCodePay.do",weChatPay).Result.Data.ToString();
}
/// <summary>
/// 小程序码
/// </summary>
/// <param name="token"></param>
/// <param name="unlimitedQrCode"></param>
/// <returns></returns>
public static Stream UnlimitedQrCode(string token,UnlimitedQrCodeModel unlimitedQrCode)
{
return RequestHelper
.PostFileStream<UnlimitedQrCodeModel>(
$"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={token}", unlimitedQrCode).Result;
}
/// <summary>
/// 一次性订阅消息
/// </summary>
/// <param name="token"></param>
/// <param name="subscribeMessage"></param>
/// <returns></returns>
public static WeChatResponse SubscribeMessage(string token,SubscribeMessageModel subscribeMessage)
{
return RequestHelper
.PostEntity<WeChatResponse, SubscribeMessageModel>(
$"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={token}", subscribeMessage).Result;
}
}
}

@ -1,131 +0,0 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using PEIS.Common.Helper.Response;
namespace PEIS.Common.Middleware
{
public class JwtMiddleware
{
private readonly RequestDelegate _next;
private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
private static IConfiguration Configuration { get; set; }
public JwtMiddleware(RequestDelegate next, IConfiguration config)
{
_next = next;
Configuration = config;
}
public async Task Invoke(HttpContext context)
{
if (context == null) throw new ArgumentNullException(nameof(context));
var tokenStr = context.Request.Headers["Authorization"].ToString();
//未携带token请求不需要授权页面,让其直接通过,用方法名上面的校验来判断
if (!string.IsNullOrEmpty(tokenStr))
{
//携带了token,判断token,回传失效,过期,或者续期
var setting = new JsonSerializerSettings
{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
//token 是否合规
if (!IsCanReadToken(ref tokenStr))
{
var result = new ResultModel() { Message = "invalid token", Code = Convert.ToInt32(ResponseHelper.ErrorEnum.TokenError) };
await context.Response.WriteAsync( JsonConvert.SerializeObject(result, setting), Encoding.UTF8);
return;
}
// token是否超过有效期
if (IsExp(tokenStr))
{
var result = new ResultModel() { Message = "token expired", Code = Convert.ToInt32(ResponseHelper.ErrorEnum.TokenError) };
await context.Response.WriteAsync( JsonConvert.SerializeObject(result, setting), Encoding.UTF8);
return;
}
var oldClaims = GetJwtSecurityToken(tokenStr).Claims;
var claims = new Claim[oldClaims?.Count() ?? 0];
for (var i = 0; i < (oldClaims?.Count() ?? 0); i++)
{
claims[i] = new Claim(oldClaims.ToList()[i].Type, oldClaims.ToList()[i].Value);
}
// 获取SecurityKey
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("Authentication")["SecurityKey"]));
var token = new JwtSecurityToken(
issuer: Configuration.GetSection("Authentication")["IsSure"], // 发布者
audience: Configuration.GetSection("Authentication")["Audience"], // 接收者
notBefore: DateTime.Now, // token签发时间
expires: DateTime.Now.AddMinutes(30), // token过期时间
claims: claims, // 该token内存储的自定义字段信息
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256) // 用于签发token的秘钥算法
);
// 返回成功信息,写出token
var data = new JwtSecurityTokenHandler().WriteToken(token);
context.Response.Headers.Add("newToken", data);
}
await _next(context);
}
/// <summary>
/// Token是否是符合要求的标准 Json Web 令牌
/// </summary>
/// <param name="tokenStr"></param>
/// <returns></returns>
public bool IsCanReadToken(ref string tokenStr)
{
tokenStr = tokenStr.Replace("Bearer ", string.Empty);
var key = Encoding.UTF8.GetBytes(Configuration.GetSection("Authentication")["SecurityKey"]);
var tokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = Configuration.GetSection("Authentication")["IsSure"],
ValidAudience = Configuration.GetSection("Authentication")["Audience"],
IssuerSigningKey = new SymmetricSecurityKey(key),
RequireExpirationTime = true,
ClockSkew = TimeSpan.Zero
};
// 验证token是否有效,如果过期,报错SecurityTokenExpiredException
// 报错信息:IDX10223 : Lifetime validation failed
try
{
var principal = _jwtSecurityTokenHandler.ValidateToken(tokenStr, tokenValidationParameters, out var securityToken);
return principal != null;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 从Token解密出JwtSecurityToken,JwtSecurityToken : SecurityToken
/// </summary>
/// <param name="tokenStr"></param>
/// <returns></returns>
public JwtSecurityToken GetJwtSecurityToken(string tokenStr)
{
var jwt = _jwtSecurityTokenHandler.ReadJwtToken(tokenStr);
return jwt;
}
/// <summary>
/// 判断token是否过期
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
public bool IsExp(string token)
{
return GetDateTime(Convert.ToDouble(GetJwtSecurityToken(token)?.Claims.First(c => c.Type == JwtRegisteredClaimNames.Exp)?.Value)) < DateTime.Now;
}
private static DateTime GetDateTime(double timeStamp)// 时间戳Timestamp转换成日期
{
var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(timeStamp).ToLocalTime();
return dateTime;
}
}
}

@ -1,30 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="true"
internalLogLevel="Off" internalLogFile="log\console.log">
<targets>
<target name="console" xsi:type="ColoredConsole"
layout="${date:format=HH\:mm\:ss}> ${message}"/>
<!--VS输出窗口-->
<target name="debugger" xsi:type="Debugger"
layout="${date:format=HH\:mm\:ss} | ${level:padding=-5} | ${message}" />
<target name="info" xsi:type="File" fileName="${basedir}/Logs/Info/${shortdate}/info.txt" layout="${date:format=HH\:mm\:ss} | ${level:padding=-5} | ${message}" />
<!--保存至文件-->
<target name="error_file" xsi:type="File" maxArchiveFiles="30"
fileName="${basedir}/Logs/Error/${shortdate}/error.txt"
layout="${longdate} | ${level:uppercase=false:padding=-5} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="debugger" />
<logger name="*" minlevel="Info" writeTo="info" />
<logger name="*" minlevel="Error" writeTo="error_file" />
</rules>
</nlog>

@ -1,41 +0,0 @@
# .net core 3.1 web Api 帮助类合集
1. Auth(Jwt相关的帮助类):
- AuthHelper
- JwtHelper
2. Cache(缓存) 适用于web Api的项目,需要传入IMemoryCache
- CacheHelper
3. Code(二维码) 生成二维码的帮助类,可以生成带标题,图标的二维码以及空二维码
- CodeHelper
4. Encryption(加解密)
- AppSettingJsonHelper web Api的配置帮助类
- ConnectionStringHelper 连接字符串解密(EF的)
- DesHelper Des加解密
- RsaHelper 公私钥加解密
5. Entity (实体类型的一些互相转换) => 反射来实现
- ModelToEntity
6. Excel 读取excel的操作
- ExcelHelper
7. File 对于文件的操作 (文件的删除创建判断存在之类的)
- FileHelper
8. Nlog 日志的帮助类
- LogHelper
9. Page 分页的帮助类
- PageHelper
10. Redis
- RedisHelper Redis的帮助类
11. Request http get post 的各种请求以及返回回来不同类型的参数
- RequestHelper
12. Response 返回的规范定义 所有接口返回值必须返回这个类型
- ResponseHepler
13. SqlServer sqlserver的原生操作 (推荐观看)
- SqlHelper
14. StringText 字符的相关操作类
- CodeHelper 获取文本数字码(不是文本里面的数字,数字码意义自己搜索)
- PinYinHelper 获取首字母之类的
- TypeChange 流的转换
15. Verify 验证
- IdCardHelper 身份证验证
16. WeChat 微信的帮助类,调用微信接口的(可以看,不要尝试,会影响我们正式业务,token会互冲)

@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace PEIS.Repositories.Context
{
/// <summary>
/// 上下文存放地方 存放数据库的上下文,不同数据库请用不同文件夹区分
/// </summary>
public class SampleContext
{
}
}

@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace PEIS.Repositories.Dtos
{
/// <summary>
/// 返回给前端的实体对象,因为在Domain层没有引用所以跟Models分开
/// </summary>
public class SampleDto
{
}
}

@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace PEIS.Repositories.Enums
{
/// <summary>
/// 枚举类存放的地方 特别是一些审核状态 下方代码举例
/// </summary>
public enum ConfigEnum
{
/// <summary>
/// 通过申请
/// </summary>
Pass = 1,
/// <summary>
/// 驳回申请
/// </summary>
Reject = 2,
/// <summary>
/// 无需审核--永久申请
/// </summary>
NoReviewRequired = 3,
}
}

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace PEIS.Repositories
{
public interface IRepository<TEntity> where TEntity :class
{
TEntity Get(int id);
IEnumerable<TEntity> GetAll();
IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
void Add(TEntity entity);
void AddRange(IEnumerable<TEntity> entities);
void Remove(TEntity entity);
void RemoveRange(IEnumerable<TEntity> entities);
}
}

@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace PEIS.Repositories.Models
{
/// <summary>
/// 存放业务逻辑实体的地方 这个为示例文件,可以删除
/// </summary>
public class Sample
{
}
}

@ -1,53 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
namespace PEIS.Repositories
{
public class Repository<TEntity> :IRepository<TEntity> where TEntity:class
{
public readonly DbContext Context;
public Repository(DbContext context)
{
Context = context;
}
public TEntity Get(int id)
{
return Context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> GetAll()
{
return Context.Set<TEntity>().ToList();
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return Context.Set<TEntity>().Where(predicate);
}
public void Add(TEntity entity)
{
Context.Set<TEntity>().Add(entity);
}
public void AddRange(IEnumerable<TEntity> entities)
{
Context.Set<TEntity>().AddRange(entities);
}
public void Remove(TEntity entity)
{
Context.Set<TEntity>().Remove(entity);
}
public void RemoveRange(IEnumerable<TEntity> entities)
{
Context.Set<TEntity>().RemoveRange(entities);
}
}
}

@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace PEIS.Service.Domain
{
/// <summary>
/// 业务逻辑帮助类 需要在业务逻辑的基础上提炼出来的一些公共方法,但不属于基础帮助类的方法
/// </summary>
public class SampleDomain
{
}
}

@ -1,12 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace PEIS.Service.IService
{
interface ISampleService
{
}
}

@ -1,19 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.EntityFrameworkCore;
using PEIS.Repositories;
using PEIS.Repositories.Models;
using PEIS.Service.IService;
namespace PEIS.Service.Service
{
public class SampleService:Repository<Sample>,ISampleService
{
public SampleService(DbContext context) : base(context)
{
}
}
}

@ -1,43 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32825.248
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PEIS.Common", "PEIS.Common\PEIS.Common.csproj", "{13B248F1-75F7-4358-9579-CF51BCA6E75B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PEIS.Repositories", "PEIS.Repositories\PEIS.Repositories.csproj", "{84CA4853-1143-4DE3-8477-14BD7811EF90}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PEIS.Cloud", "PEIS.Cloud\PEIS.Cloud.csproj", "{F857C34E-7B36-478B-9374-1DF2901E7224}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PEIS.Service", "PEIS.Service\PEIS.Service.csproj", "{0467DFB2-3B4D-466F-93A9-8170E38A7DEE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{13B248F1-75F7-4358-9579-CF51BCA6E75B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{13B248F1-75F7-4358-9579-CF51BCA6E75B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{13B248F1-75F7-4358-9579-CF51BCA6E75B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{13B248F1-75F7-4358-9579-CF51BCA6E75B}.Release|Any CPU.Build.0 = Release|Any CPU
{84CA4853-1143-4DE3-8477-14BD7811EF90}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{84CA4853-1143-4DE3-8477-14BD7811EF90}.Debug|Any CPU.Build.0 = Debug|Any CPU
{84CA4853-1143-4DE3-8477-14BD7811EF90}.Release|Any CPU.ActiveCfg = Release|Any CPU
{84CA4853-1143-4DE3-8477-14BD7811EF90}.Release|Any CPU.Build.0 = Release|Any CPU
{F857C34E-7B36-478B-9374-1DF2901E7224}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F857C34E-7B36-478B-9374-1DF2901E7224}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F857C34E-7B36-478B-9374-1DF2901E7224}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F857C34E-7B36-478B-9374-1DF2901E7224}.Release|Any CPU.Build.0 = Release|Any CPU
{0467DFB2-3B4D-466F-93A9-8170E38A7DEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0467DFB2-3B4D-466F-93A9-8170E38A7DEE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0467DFB2-3B4D-466F-93A9-8170E38A7DEE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0467DFB2-3B4D-466F-93A9-8170E38A7DEE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3615424A-8F6D-4912-B462-23042E651E6E}
EndGlobalSection
EndGlobal
Loading…
Cancel
Save