commit 865b20d5d4c1790e01665dd2fbc2c46996df85f3 Author: xRain Date: Mon Dec 23 16:32:06 2019 +0800 remove nuget key from ci diff --git a/.github/workflows/dotnetcore.yml b/.github/workflows/dotnetcore.yml new file mode 100644 index 0000000..cf0c8a2 --- /dev/null +++ b/.github/workflows/dotnetcore.yml @@ -0,0 +1,16 @@ +name: .NET Core + +on: [push] + +jobs: + build: + name: publish to nuget + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 2 + - name: Publish NuGet + uses: rohith/publish-nuget@v1.0.3 + with: + nuget_key: "oy2jz2ls4vmy5sob3gyqv27spaslvibuzlpwitzvyzptzq" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6efe9d9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,435 @@ +# Created by .ignore support plugin (hsz.mobi) +### C template +# Prerequisites +*.d + +# Object files +*.o +*.ko +*.obj +*.elf + +# Linker output +*.ilk +*.map +*.exp + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf + +### macOS template +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### VisualStudio template +## 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/master/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/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# 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/ + +# 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 +*.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 + +# 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 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/ + +# 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/ + diff --git a/Communications/Base.cs b/Communications/Base.cs new file mode 100644 index 0000000..a9cc3d6 --- /dev/null +++ b/Communications/Base.cs @@ -0,0 +1,98 @@ +using System.Collections.Generic; +using System.Text.Json; +using System.Text.Json.Serialization; +using Newtonsoft.Json.Serialization; + +namespace YYApi.Communications +{ + public class BaseResponse + { + /// + /// 错误代码 + /// + public int Code { get; set; } + + /// + /// 错误描述 + /// + public string Message { get; set; } + + /// + /// 默认错误代码对应提示信息 + /// + private readonly Dictionary MsgBox = new Dictionary() + { + {200, "成功"}, + {400, "参数错误"}, + {401, "需要登录"}, + {403, "无权访问"}, + {404, "接口不存在"}, + {500, "服务器错误"} + }; + + /// + /// 返回一个成功的空结果 + /// + public BaseResponse() + { + SetCode(200); + } + + /// + /// 返回指定代码的描述 + /// + /// 错误代码 + public BaseResponse(int code) + { + SetCode(code); + } + + /// + /// 返回指定代码的结果,并自定义提示信息 + /// + /// 错误代码 + /// 错误信息 + public BaseResponse(int code, string message) + { + SetCodeMsg(code, message); + } + + /// + /// 设置响应结果的错误代码 + /// + /// 错误代码 + public void SetCode(int code) + { + Code = code; + Message = MsgBox.ContainsKey(code) ? MsgBox[code] : "未知错误"; + } + + /// + /// 设置响应结果的错误代码和错误描述 + /// + /// 错误代码 + /// 错误描述 + public void SetCodeMsg(int code, string message) + { + SetCode(code); + if (!string.IsNullOrEmpty(message)) + { + Message = message; + } + } + + /// + /// 序列化为JSON字符串 + /// + /// + public override string ToString() + { + return JsonSerializer.Serialize(this, new JsonSerializerOptions + { + IgnoreReadOnlyProperties = true, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Converters = {new JsonStringEnumConverter()} + }); + } + } +} \ No newline at end of file diff --git a/Controllers/BaseController.cs b/Controllers/BaseController.cs new file mode 100644 index 0000000..74e5f21 --- /dev/null +++ b/Controllers/BaseController.cs @@ -0,0 +1,79 @@ +using YYApi.Communications; +using YYApi.Helpers; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using System.Linq; + +namespace YYApi.Controllers +{ + /// + /// 基础控制器,所有控制器均继承本控制器 + /// 1. 自动验证请求参数 + /// 2. 报错返回 + /// 3. 错误回馈页面 + /// + public class BaseController : Controller + { + protected int LoginId => int.Parse(HttpContext.Items["LoginId"].ToString()); + + /// + /// 验证请求参数 + /// + /// + public override void OnActionExecuting(ActionExecutingContext context) + { + if (!context.ModelState.IsValid) + { + foreach (var item in context.ModelState.Values) + { + if (item.ValidationState == ModelValidationState.Invalid) + { + Error(400, item.Errors.First().ErrorMessage); + break; + } + } + } + } + + + /// + /// 错误返回 + /// + /// 错误代码 + /// 错误描述(若是常规错误,代码可自动带取描述) + /// + protected static void Error(int code, string message = null) + { + throw new ApiException(code, message); + } + + /// + /// 检测条件,根据条件返回报错 + /// + /// 检测条件 + /// 错误代码 + /// 错误描述 + protected static void ErrorWhen(bool condition, int code, string message = null) + { + if (condition) + { + Error(code, message); + } + } + + /// + /// 错误回馈页面 + /// + /// 错误代码 + /// + [HttpGet("exception/{code:int}")] + [ApiExplorerSettings(IgnoreApi = true)] + public BaseResponse ExceptionHandler(int code) + { + var response = new BaseResponse(); + response.SetCode(code); + return response; + } + } +} \ No newline at end of file diff --git a/Extensions.cs b/Extensions.cs new file mode 100644 index 0000000..52f8467 --- /dev/null +++ b/Extensions.cs @@ -0,0 +1,143 @@ +using System; +using YYApi.Helpers; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerUI; + +namespace YYApi +{ + /// + /// 加入系统的扩展信息 + /// + public static class Extensions + { + /// + /// 添加自定义授权认证中间价 + /// + /// + /// + public static IServiceCollection AddAuth(this IServiceCollection builder) + { + return builder.AddScoped(); + } + + /// + /// 添加整个YYAPI + /// + /// + /// + /// + /// + public static IServiceCollection AddYYApi(this IServiceCollection builder, string title, + string description = null) + { + return builder.AddAuth().AddApiDoc(title, description); + } + + /// + /// 添加Api文档服务 + /// + /// + /// 文档标题 + /// 文档描述 + /// + public static IServiceCollection AddApiDoc(this IServiceCollection builder, string title, + string description = null) + { + return builder.AddSwaggerGen(x => + { + x.SwaggerDoc("api", new OpenApiInfo {Title = title, Description = description}); + x.EnableAnnotations(); + x.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference {Type = ReferenceType.SecurityScheme, Id = "HeaderToken"} + }, + new[] {"readAccess", "writeAccess"} + } + }); + x.AddSecurityDefinition("HeaderToken", + new OpenApiSecurityScheme {Name = "Token", In = ParameterLocation.Header}); + }); + } + + /// + /// 使用异常中间价扩展 + /// + /// + /// + public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } + + /// + /// 使用文档UI + /// + /// + /// 文档标题 + /// 文档支持的提交方式(如果不指定,默认使用POST) + /// + public static IApplicationBuilder UseApiDoc(this IApplicationBuilder builder, string title, + params SubmitMethod[] submitMethods) + { + return builder.UseSwagger(x => x.RouteTemplate = "docs/{documentName}.json").UseSwaggerUI(x => + { + x.RoutePrefix = "docs"; + x.DocumentTitle = title; + x.SwaggerEndpoint("/docs/api.json", name: title); + x.EnableValidator(); + if (submitMethods.Length > 0) + { + x.SupportedSubmitMethods(submitMethods); + } + else + { + x.SupportedSubmitMethods(SubmitMethod.Post); + } + + x.DisplayRequestDuration(); + }); + } + + + /// + /// 同时使用Api文档和异常处理中间件 + /// + /// + /// 文档标题 + /// API提交方式定义 + /// + public static IApplicationBuilder UseDocAndException(this IApplicationBuilder builder, string title = "API文档", + params SubmitMethod[] submitMethods) + { + return builder.UseExceptionMiddleware().UseApiDoc(title, submitMethods); + } + + /// + /// 使用自定义认证中间件(依赖IDistributedCache) + /// + /// + /// + public static IApplicationBuilder UseAuthMiddleware(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } + + /// + /// 使用所有YYApi自定义中间件 + /// + /// + /// + /// + /// + public static IApplicationBuilder UseYYApiMiddleware(this IApplicationBuilder builder, string title = "API文档", + params SubmitMethod[] submitMethods) + { + return builder.UseExceptionMiddleware().UseApiDoc(title, submitMethods).UseMiddleware(); + } + } +} \ No newline at end of file diff --git a/Helpers/ApiDoc.cs b/Helpers/ApiDoc.cs new file mode 100644 index 0000000..4c713fb --- /dev/null +++ b/Helpers/ApiDoc.cs @@ -0,0 +1,23 @@ +using Swashbuckle.AspNetCore.Annotations; + +namespace YYApi.Helpers +{ + /// + /// 快捷自定义接口文档类 + /// + public class ApiDoc : SwaggerOperationAttribute + { + /// + /// 定义接口说明 + /// + /// 接口分组 + /// 接口名称 + public ApiDoc(string tag, string name) + { + Tags = new[] {tag}; + Summary = name; + // Consumes = new[] {"application/json"}; + // Produces = new[] {"application/json"}; + } + } +} \ No newline at end of file diff --git a/Helpers/AuthMiddleware.cs b/Helpers/AuthMiddleware.cs new file mode 100644 index 0000000..0153453 --- /dev/null +++ b/Helpers/AuthMiddleware.cs @@ -0,0 +1,85 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.Extensions.Caching.Distributed; + +namespace YYApi.Helpers +{ + /// + /// 认证信息获取中间件 + /// + public class AuthMiddleware + { + private RequestDelegate Next { get; } + + public AuthMiddleware(RequestDelegate next) + { + Next = next; + } + + public Task Invoke(HttpContext httpContext, IDistributedCache cache) + { + string token = null; + if (httpContext.Request.Headers.ContainsKey("Token")) + { + token = httpContext.Request.Headers["Token"]; + } + + if (!string.IsNullOrEmpty(token)) + { + var id = cache.GetString(token); + if (id != null) + { + httpContext.Items.Add("LoginId", id); + } + } + + return Next(httpContext); + } + } + + /// + /// 检测登录中间件 + /// + public class CheckAuthAttribute : ActionFilterAttribute + { + public override void OnActionExecuting(ActionExecutingContext context) + { + if (context.HttpContext.Items["LoginId"] == null) + { + throw new ApiException(401); + } + } + } + + /// + /// 认证助手 + /// + public class Auth + { + private IDistributedCache Cache { get; } + + public Auth(IDistributedCache cache) + { + Cache = cache; + } + + /// + /// 产生一个Token记录并返回Token + /// + /// + /// + public string SetId(int id) + { + var uuid = GetUUID(); + Cache.SetString(uuid, id.ToString()); + return uuid; + } + + private string GetUUID() + { + return Guid.NewGuid().ToString(); + } + } +} \ No newline at end of file diff --git a/Helpers/ExceptionMiddleware.cs b/Helpers/ExceptionMiddleware.cs new file mode 100644 index 0000000..80bac57 --- /dev/null +++ b/Helpers/ExceptionMiddleware.cs @@ -0,0 +1,71 @@ +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using YYApi.Communications; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Logging; + +namespace YYApi.Helpers +{ + /// + /// 异常处理中间件 + /// + public class ExceptionMiddleware + { + private RequestDelegate Next { get; } + private ILogger Log { get; } + + public ExceptionMiddleware(RequestDelegate next, ILogger log) + { + Log = log; + Next = next; + } + + public async Task InvokeAsync(HttpContext context) + { + var response = new BaseResponse(); + try + { + await Next(context); + } + catch (ApiException ex) + { + response.SetCodeMsg(ex.Code, ex.Message); + ErrorResponse(context, response); + } + catch (Exception ex) + { + Log.LogError(ex.Message); + Log.LogError(ex.StackTrace); + response.SetCodeMsg(500, ex.Message); + ErrorResponse(context, response); + } + } + + /// + /// 异常抛出错误 + /// + /// + /// + private void ErrorResponse(HttpContext context, BaseResponse response) + { + context.Response.StatusCode = 200; + context.Response.Headers.Add("Content-Type", "application/json"); + context.Response.WriteAsync(response.ToString()); + } + } + + + /// + /// Api错误捕获异常 + /// + public class ApiException : Exception + { + public int Code { get; } + + public ApiException(int code, string message = "") : base(message) + { + Code = code; + } + } +} \ No newline at end of file diff --git a/Helpers/Util.cs b/Helpers/Util.cs new file mode 100644 index 0000000..ce386af --- /dev/null +++ b/Helpers/Util.cs @@ -0,0 +1,41 @@ +using System; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; + +namespace YYApi.Helpers +{ + public static class Util + { + /// + /// 检测手机号是否正确 + /// + /// 手机号码 + /// + public static bool CheckCell(string cell) + { + var regex = new Regex("^1[34578]\\d{9}$"); + return regex.IsMatch(cell); + } + + /// + /// MD5加密字符串 + /// + /// 源字符串 + /// 加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位 + /// + public static string Md5(string source, string mode = "x2") + { + byte[] sor = Encoding.UTF8.GetBytes(source); + MD5 md5 = MD5.Create(); + byte[] result = md5.ComputeHash(sor); + StringBuilder strbul = new StringBuilder(40); + for (int i = 0; i < result.Length; i++) + { + strbul.Append(result[i].ToString(mode)); + } + + return strbul.ToString(); + } + } +} \ No newline at end of file diff --git a/Properties/launchSettings.json b/Properties/launchSettings.json new file mode 100644 index 0000000..178c853 --- /dev/null +++ b/Properties/launchSettings.json @@ -0,0 +1,6 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..c556700 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# YYApi diff --git a/YYApi.csproj b/YYApi.csproj new file mode 100644 index 0000000..0936947 --- /dev/null +++ b/YYApi.csproj @@ -0,0 +1,39 @@ + + + + netcoreapp3.1 + Library + true + 0.0.2 + xRain@YYTech + AspNetCore一个方便的API文档,捕获异常,统一输入输出的API类库 + YY-Tech.YYApi + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + +