From f204b211b90cae3d5db4efc8d84a08c8bcc572d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A9=99=E5=AD=90?= <454313500@qq.com> Date: Tue, 12 Oct 2021 16:52:28 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=89=A9=E5=B1=95=E4=B8=AD?= =?UTF-8?q?=E9=97=B4=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/UserController.cs | 22 +++ .../Yi.Framework.ApiMicroservice/Program.cs | 3 +- .../Yi.Framework.ApiMicroservice/Startup.cs | 97 ++++++++--- .../Utility/CustomAutofacAop.cs | 20 +++ .../Utility/CustomAutofacModule.cs | 64 +++++++ .../Utility/CustomHostingStartup.cs | 54 ++++++ .../WeatherForecast.cs | 15 -- .../Yi.Framework.ApiMicroservice.csproj | 5 + .../IOCOptions}/ConsulClientOption.cs | 2 +- .../IOCOptions}/ConsulRegisterOption.cs | 2 +- Yi.Framework/Yi.Framework.Core/Class1.cs | 9 - .../ClienExtend/AbstractConsulDispatcher.cs | 2 +- .../ClienExtend/AverageDispatcher.cs | 3 +- .../ClienExtend/WeightDispatcher.cs | 2 +- .../Yi.Framework.WebCore/Appsettings.cs | 69 ++++++++ Yi.Framework/Yi.Framework.WebCore/Class1.cs | 8 - .../Yi.Framework.WebCore/CommonExtend.cs | 76 +++++---- .../FilterExtend/CORSFilter.cs | 37 +++-- .../CustomAction2CommitFilterAttribute.cs | 14 +- .../CustomActionCacheFilterAttribute.cs | 59 +++---- .../CustomActionCheckFilterAttribute.cs | 84 +++++----- .../CustomExceptionFilterAttribute.cs | 5 +- .../CustomIOCFilterFactoryAttribute.cs | 50 +++--- .../CustomResourceFilterAttribute.cs | 88 +++++----- .../FilterExtend/LogActionFilterAttribute.cs | 5 +- .../MiddlewareExtend}/ConsulRegiterExtend.cs | 25 +-- .../MiddlewareExtend/CorsExtension.cs | 34 ++++ .../MiddlewareExtend/DataBaseExtension.cs | 27 +++ .../MiddlewareExtend/ErrorHandExtension.cs | 75 +++++++++ .../MiddlewareExtend/HealthCheckExtension.cs} | 7 +- ...leware.cs => PreOptionRequestExtension.cs} | 12 +- .../MiddlewareExtend/StaticPageExtension.cs | 156 ++++++++++++++++++ .../MiddlewareExtend/StaticPageMiddleware.cs | 156 ------------------ .../MiddlewareExtend/SwaggerExtension.cs | 76 +++++++++ 34 files changed, 921 insertions(+), 442 deletions(-) create mode 100644 Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomAutofacAop.cs create mode 100644 Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomAutofacModule.cs create mode 100644 Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomHostingStartup.cs delete mode 100644 Yi.Framework/Yi.Framework.ApiMicroservice/WeatherForecast.cs rename Yi.Framework/{Yi.Framework.Core/ConsulExtend => Yi.Framework.Common/IOCOptions}/ConsulClientOption.cs (86%) rename Yi.Framework/{Yi.Framework.Core/ConsulExtend/ServerExtend => Yi.Framework.Common/IOCOptions}/ConsulRegisterOption.cs (95%) delete mode 100644 Yi.Framework/Yi.Framework.Core/Class1.cs create mode 100644 Yi.Framework/Yi.Framework.WebCore/Appsettings.cs delete mode 100644 Yi.Framework/Yi.Framework.WebCore/Class1.cs rename Yi.Framework/{Yi.Framework.Core/ConsulExtend/ServerExtend => Yi.Framework.WebCore/MiddlewareExtend}/ConsulRegiterExtend.cs (67%) create mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/CorsExtension.cs create mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DataBaseExtension.cs create mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ErrorHandExtension.cs rename Yi.Framework/{Yi.Framework.Core/ConsulExtend/ServerExtend/HealthCheckMiddleware.cs => Yi.Framework.WebCore/MiddlewareExtend/HealthCheckExtension.cs} (84%) rename Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/{PreOptionRequestMiddleware.cs => PreOptionRequestExtension.cs} (63%) create mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/StaticPageExtension.cs delete mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/StaticPageMiddleware.cs create mode 100644 Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/SwaggerExtension.cs diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Controllers/UserController.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Controllers/UserController.cs index ec29bf60..1dfd90a3 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/Controllers/UserController.cs +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Controllers/UserController.cs @@ -23,11 +23,21 @@ namespace Yi.Framework.ApiMicroservice.Controllers _userService = userService; } + /// + /// 查 + /// + /// [HttpGet] public async Task GetUser() { return Result.Success().SetData(await _userService.GetAllEntitiesTrueAsync()); } + + /// + /// 更 + /// + /// + /// [HttpPut] public async Task UpdateUser(user _user) { @@ -35,12 +45,24 @@ namespace Yi.Framework.ApiMicroservice.Controllers return Result.Success(); } + + /// + /// 删 + /// + /// + /// [HttpDelete] public async Task DelListUser(List _ids) { await _userService.DelListByUpdateAsync(_ids); return Result.Success(); } + + /// + /// 增 + /// + /// + /// [HttpPost] public async Task AddUser(user _user) { diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Program.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Program.cs index 6543d16f..12bd5248 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/Program.cs +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Program.cs @@ -1,3 +1,4 @@ +using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; @@ -21,6 +22,6 @@ namespace Yi.Framework.ApiMicroservice .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); - }); + }).UseServiceProviderFactory(new AutofacServiceProviderFactory()); } } diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs index 2a27d34a..07bfa7b6 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Startup.cs @@ -1,3 +1,4 @@ +using Autofac; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; @@ -12,10 +13,12 @@ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Yi.Framework.ApiMicroservice.Utility; using Yi.Framework.Common.IOCOptions; using Yi.Framework.Interface; using Yi.Framework.Model; using Yi.Framework.Service; +using Yi.Framework.WebCore.MiddlewareExtend; namespace Yi.Framework.ApiMicroservice { @@ -24,7 +27,6 @@ namespace Yi.Framework.ApiMicroservice public Startup(IConfiguration configuration) { Configuration = configuration; - } public IConfiguration Configuration { get; } @@ -32,48 +34,97 @@ namespace Yi.Framework.ApiMicroservice // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - + #region + //+ + #endregion services.AddControllers(); - services.AddCors(options => options.AddPolicy("CorsPolicy",// -builder => -{ - builder.AllowAnyMethod() - .SetIsOriginAllowed(_ => true) - .AllowAnyHeader() - .AllowCredentials(); -})); - services.Configure(this.Configuration.GetSection("SqliteConn")); - services.AddScoped(); - services.AddScoped(typeof(IBaseService<>),typeof(BaseService<>)); + #region + //Swagger + #endregion + services.AddSwaggerService(); + #region + // + #endregion + services.AddCorsService(); + + #region + //ݿ + #endregion + services.AddDataBaseService("SqliteConn"); + + //ЩӦԶע services.AddScoped(); services.AddScoped(); - services.AddSwaggerGen(c => - { - c.SwaggerDoc("v1", new OpenApiInfo { Title = "Yi.Framework.ApiMicroservice", Version = "v1" }); - }); + } - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + #region Autofacע + public void ConfigureContainer(ContainerBuilder containerBuilder) { - if (env.IsDevelopment()) + #region + //Moduleע + #endregion + containerBuilder.RegisterModule(); + } + #endregion + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public async void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + //if (env.IsDevelopment()) { + #region + //ҳע + #endregion app.UseDeveloperExceptionPage(); - app.UseSwagger(); - app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Yi.Framework.ApiMicroservice v1")); + + #region + //Swaggerע + #endregion + app.UseSwaggerService(); } + #region + //HttpsRedirectionע + #endregion app.UseHttpsRedirection(); + #region + //·ע + #endregion app.UseRouting(); - app.UseCors("CorsPolicy"); + + #region + //ע + #endregion + app.UseCorsService(); + + #region + //ע + #endregion + app.UseHealthCheckMiddleware(); + + #region + //Ȩע + #endregion app.UseAuthentication(); + + #region + //Ȩע + #endregion app.UseAuthorization(); + #region + //Consulע + #endregion + await app.UseConsulService(); + #region + //Endpointsע + #endregion app.UseEndpoints(endpoints => { endpoints.MapControllers(); diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomAutofacAop.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomAutofacAop.cs new file mode 100644 index 00000000..6dba1144 --- /dev/null +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomAutofacAop.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Yi.Framework.ApiMicroservice.Utility +{ + public class CustomAutofacAop : IInterceptor + { + public void Intercept(IInvocation invocation) + { + Console.WriteLine($"invocation.Methond={invocation.Method}"); + Console.WriteLine($"invocation.Arguments={string.Join(",", invocation.Arguments)}"); + + invocation.Proceed(); //继续执行 + + Console.WriteLine($"方法{invocation.Method}执行完成了"); + } + } +} diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomAutofacModule.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomAutofacModule.cs new file mode 100644 index 00000000..3f1dd70f --- /dev/null +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomAutofacModule.cs @@ -0,0 +1,64 @@ +using Autofac; +using Autofac.Extras.DynamicProxy; +using Castle.DynamicProxy; +using Microsoft.AspNetCore.Mvc.ApplicationParts; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using Yi.Framework.ApiMicroservice.Utility; +using Yi.Framework.Interface; +using Yi.Framework.Model; +using Yi.Framework.Service; +using Module = Autofac.Module; + +namespace Yi.Framework.ApiMicroservice.Utility +{ + public class CustomAutofacModule : Module + { + protected override void Load(ContainerBuilder containerBuilder) + { + //var assembly = this.GetType().GetTypeInfo().Assembly; + //var builder = new ContainerBuilder(); + //var manager = new ApplicationPartManager(); + //manager.ApplicationParts.Add(new AssemblyPart(assembly)); + //manager.FeatureProviders.Add(new ControllerFeatureProvider()); + //var feature = new ControllerFeature(); + //manager.PopulateFeature(feature); + //builder.RegisterType().AsSelf().SingleInstance(); + //builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired(); + + //containerBuilder.RegisterType().As().InstancePerDependency(); 瞬态 + //containerBuilder.RegisterType().As().SingleInstance(); 单例 + //containerBuilder.RegisterType().As().InstancePerLifetimeScope(); 作用域 + + containerBuilder.Register(c => new CustomAutofacAop());//AOP注册 + //containerBuilder.RegisterType().As().EnableInterfaceInterceptors();开启Aop + + //将数据库对象注入 + containerBuilder.RegisterType().As().InstancePerLifetimeScope().EnableInterfaceInterceptors(); + + containerBuilder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>)).EnableInterfaceInterceptors(); + + } + + } +} + + +public interface IAutofacTest +{ + void Show(int id, string name); +} + +[Intercept(typeof(CustomAutofacAop))] +public class AutofacTest : IAutofacTest +{ + public void Show(int id, string name) + { + Console.WriteLine($"This is {id} _ {name}"); + } +} diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomHostingStartup.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomHostingStartup.cs new file mode 100644 index 00000000..fa8fa924 --- /dev/null +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Utility/CustomHostingStartup.cs @@ -0,0 +1,54 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +[assembly: HostingStartup(typeof(Yi.Framework.ApiMicroservice.Utility.CustomHostingStartup))] +namespace Yi.Framework.ApiMicroservice.Utility +{ + /// + /// 必须实现IHostingStartup接口 + /// 必须标记HostingStartup特性 + /// + /// 就像木马一样 + /// + public class CustomHostingStartup : IHostingStartup + { + public void Configure(IWebHostBuilder builder) + { + Console.WriteLine("This is CustomHostingStartup Invoke"); + + //有IWebHostBuilder,一切都可以做。。 + #region MyRegion + //builder.ConfigureAppConfiguration(configurationBuilder => + //{ + // configurationBuilder.AddXmlFile("appsettings1.xml", optional: false, reloadOnChange: true); + //});//添加配置 + + //builder.ConfigureServices(services => + //{ + // services.AddTransient(); + //});//IOC注册 + + //builder.Configure(app => + //{ + // app.Use(next => + // { + // Console.WriteLine("This is CustomHostingStartup-Middleware Init"); + // return new RequestDelegate( + // async context => + // { + // Console.WriteLine("This is CustomHostingStartup-Middleware start"); + // await next.Invoke(context); + // Console.WriteLine("This is CustomHostingStartup-Middleware end"); + // }); + // }); + //});//甚至来个中间件 + #endregion + } + } +} diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/WeatherForecast.cs b/Yi.Framework/Yi.Framework.ApiMicroservice/WeatherForecast.cs deleted file mode 100644 index a317faba..00000000 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/WeatherForecast.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace Yi.Framework.ApiMicroservice -{ - public class WeatherForecast - { - public DateTime Date { get; set; } - - public int TemperatureC { get; set; } - - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string Summary { get; set; } - } -} diff --git a/Yi.Framework/Yi.Framework.ApiMicroservice/Yi.Framework.ApiMicroservice.csproj b/Yi.Framework/Yi.Framework.ApiMicroservice/Yi.Framework.ApiMicroservice.csproj index 43ddcbd9..8a5f2724 100644 --- a/Yi.Framework/Yi.Framework.ApiMicroservice/Yi.Framework.ApiMicroservice.csproj +++ b/Yi.Framework/Yi.Framework.ApiMicroservice/Yi.Framework.ApiMicroservice.csproj @@ -4,6 +4,11 @@ net5.0 + + D:\CC.Yi\CC.Yi\Yi.Framework\Yi.Framework.ApiMicroservice\Yi.Framework.ApiMicroservice.xml + 1701;1702;CS1591 + + all diff --git a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ConsulClientOption.cs b/Yi.Framework/Yi.Framework.Common/IOCOptions/ConsulClientOption.cs similarity index 86% rename from Yi.Framework/Yi.Framework.Core/ConsulExtend/ConsulClientOption.cs rename to Yi.Framework/Yi.Framework.Common/IOCOptions/ConsulClientOption.cs index 5eebc512..a9cc27a3 100644 --- a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ConsulClientOption.cs +++ b/Yi.Framework/Yi.Framework.Common/IOCOptions/ConsulClientOption.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Text; -namespace CC.ElectronicCommerce.Core.ConsulExtend +namespace Yi.Framework.Common.IOCOptions { /// /// 使用Consul时需要配置 diff --git a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/ConsulRegisterOption.cs b/Yi.Framework/Yi.Framework.Common/IOCOptions/ConsulRegisterOption.cs similarity index 95% rename from Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/ConsulRegisterOption.cs rename to Yi.Framework/Yi.Framework.Common/IOCOptions/ConsulRegisterOption.cs index 0cb6847d..a5c4fa6a 100644 --- a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/ConsulRegisterOption.cs +++ b/Yi.Framework/Yi.Framework.Common/IOCOptions/ConsulRegisterOption.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace CC.ElectronicCommerce.Core.ConsulExtend +namespace Yi.Framework.Common.IOCOptions { public class ConsulRegisterOption { diff --git a/Yi.Framework/Yi.Framework.Core/Class1.cs b/Yi.Framework/Yi.Framework.Core/Class1.cs deleted file mode 100644 index 80f6c173..00000000 --- a/Yi.Framework/Yi.Framework.Core/Class1.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System; - -namespace Yi.Framework.Core -{ - public class Class1 - { - //终于搞好了 - } -} diff --git a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/AbstractConsulDispatcher.cs b/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/AbstractConsulDispatcher.cs index f9449e94..a34e2063 100644 --- a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/AbstractConsulDispatcher.cs +++ b/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/AbstractConsulDispatcher.cs @@ -6,7 +6,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace CC.ElectronicCommerce.Core.ConsulExtend +namespace Yi.Framework.Core.ConsulExtend { public abstract class AbstractConsulDispatcher { diff --git a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/AverageDispatcher.cs b/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/AverageDispatcher.cs index 0bd2d5da..905a6ea7 100644 --- a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/AverageDispatcher.cs +++ b/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/AverageDispatcher.cs @@ -4,8 +4,9 @@ using System.Linq; using System.Text; using Consul; using Microsoft.Extensions.Options; +using Yi.Framework.Common.IOCOptions; -namespace CC.ElectronicCommerce.Core.ConsulExtend +namespace Yi.Framework.Core.ConsulExtend { /// /// 平均 diff --git a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/WeightDispatcher.cs b/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/WeightDispatcher.cs index 9d482312..4f6b03fc 100644 --- a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/WeightDispatcher.cs +++ b/Yi.Framework/Yi.Framework.Core/ConsulExtend/ClienExtend/WeightDispatcher.cs @@ -5,7 +5,7 @@ using System.Text; using Consul; using Microsoft.Extensions.Options; -namespace CC.ElectronicCommerce.Core.ConsulExtend +namespace Yi.Framework.Core.ConsulExtend { /// /// 权重 diff --git a/Yi.Framework/Yi.Framework.WebCore/Appsettings.cs b/Yi.Framework/Yi.Framework.WebCore/Appsettings.cs new file mode 100644 index 00000000..0d639e9c --- /dev/null +++ b/Yi.Framework/Yi.Framework.WebCore/Appsettings.cs @@ -0,0 +1,69 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration.Json; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Yi.Framework.WebCore +{ + /// + /// appsettings.json操作类 + /// + public class Appsettings + { + static IConfiguration Configuration { get; set; } + static string contentPath { get; set; } + + public Appsettings(string contentPath) + { + string Path = "appsettings.json"; + + //如果你把配置文件 是 根据环境变量来分开了,可以这样写 + //Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json"; + + Configuration = new ConfigurationBuilder() + .SetBasePath(contentPath) + .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//这样的话,可以直接读目录里的json文件,而不是 bin 文件夹下的,所以不用修改复制属性 + .Build(); + } + + public Appsettings(IConfiguration configuration) + { + Configuration = configuration; + } + + /// + /// 封装要操作的字符 + /// + /// 节点配置 + /// + public static string app(params string[] sections) + { + try + { + + if (sections.Any()) + { + return Configuration[string.Join(":", sections)]; + } + } + catch (Exception) { } + + return ""; + } + + /// + /// 递归获取配置信息数组 + /// + /// + /// + /// + public static T app(params string[] sections) + { + List list = new List(); + // 引用 Microsoft.Extensions.Configuration.Binder 包 + Configuration.Bind(string.Join(":", sections), list); + return list[0]; + } + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/Class1.cs b/Yi.Framework/Yi.Framework.WebCore/Class1.cs deleted file mode 100644 index d0f3a77f..00000000 --- a/Yi.Framework/Yi.Framework.WebCore/Class1.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System; - -namespace Yi.Framework.WebCore -{ - public class Class1 - { - } -} diff --git a/Yi.Framework/Yi.Framework.WebCore/CommonExtend.cs b/Yi.Framework/Yi.Framework.WebCore/CommonExtend.cs index 0158a988..08d104d2 100644 --- a/Yi.Framework/Yi.Framework.WebCore/CommonExtend.cs +++ b/Yi.Framework/Yi.Framework.WebCore/CommonExtend.cs @@ -1,36 +1,44 @@ -//using Yi.Framework.Model; -//using Microsoft.AspNetCore.Authentication; -//using Microsoft.AspNetCore.Http; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Security.Claims; -//using System.Text; -//using System.Threading.Tasks; +using Yi.Framework.Model; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; +using Yi.Framework.Model.Models; -//namespace CC.ElectronicCommerce.WebCore -//{ -// public static class CommonExtend -// { -// public static bool IsAjaxRequest(this HttpRequest request) -// { -// string header = request.Headers["X-Requested-With"]; -// return "XMLHttpRequest".Equals(header); -// } +namespace Yi.Framework.WebCore +{ + public static class CommonExtend + { + /// + /// 判断是否为异步请求 + /// + /// + /// + public static bool IsAjaxRequest(this HttpRequest request) + { + string header = request.Headers["X-Requested-With"]; + return "XMLHttpRequest".Equals(header); + } -// /// -// /// 基于HttpContext,当前鉴权方式解析,获取用户信息 -// /// -// /// -// /// -// public static UserInfo GetCurrentUserInfo(this HttpContext httpContext) -// { -// IEnumerable claimlist = httpContext.AuthenticateAsync().Result.Principal.Claims; -// return new UserInfo() -// { -// id = long.Parse(claimlist.FirstOrDefault(u => u.Type == "id").Value), -// username = claimlist.FirstOrDefault(u => u.Type == "username").Value ?? "匿名" -// }; -// } -// } -//} + /// + /// 基于HttpContext,当前鉴权方式解析,获取用户信息 + /// + /// + /// + public static user GetCurrentUserInfo(this HttpContext httpContext) + { + IEnumerable claimlist = httpContext.AuthenticateAsync().Result.Principal.Claims; + + Int32.TryParse(claimlist.FirstOrDefault(u => u.Type == "id").Value,out int resId); + return new user() + { + id =resId, + username = claimlist.FirstOrDefault(u => u.Type == "username").Value ?? "匿名" + }; + } + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CORSFilter.cs b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CORSFilter.cs index 366cfbaa..d697230a 100644 --- a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CORSFilter.cs +++ b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CORSFilter.cs @@ -1,18 +1,21 @@ -//using Microsoft.AspNetCore.Mvc.Filters; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; -//namespace Zhaoxi.AgileFramework.WebCore.FilterExtend -//{ -// public class CORSFilter : ActionFilterAttribute -// { -// public override void OnActionExecuting(ActionExecutingContext context) -// { -// context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); -// context.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT"); -// context.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); -// } -// } -//} +namespace Yi.Framework.WebCore.FilterExtend +{ + /// + /// 跨域过滤器 + /// + public class CORSFilter : ActionFilterAttribute + { + public override void OnActionExecuting(ActionExecutingContext context) + { + context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); + context.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT"); + context.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); + } + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomAction2CommitFilterAttribute.cs b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomAction2CommitFilterAttribute.cs index 40a1d339..686f80b8 100644 --- a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomAction2CommitFilterAttribute.cs +++ b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomAction2CommitFilterAttribute.cs @@ -12,10 +12,18 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace CC.ElectronicCommerce.WebCore.FilterExtend +namespace Yi.Framework.WebCore.FilterExtend { + /// + /// 重复提交过滤器 + /// public class CustomAction2CommitFilterAttribute : ActionFilterAttribute { + /// + /// 防重复提交周期 单位秒 + /// + public int TimeOut = 1; + #region Identity private readonly ILogger _logger; private readonly CacheClientDB _cacheClientDB; @@ -28,10 +36,6 @@ namespace CC.ElectronicCommerce.WebCore.FilterExtend } #endregion - /// - /// 防重复提交周期 单位秒 - /// - public int TimeOut = 3; public override void OnActionExecuting(ActionExecutingContext context) { diff --git a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomActionCacheFilterAttribute.cs b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomActionCacheFilterAttribute.cs index 3a41fead..cf976d29 100644 --- a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomActionCacheFilterAttribute.cs +++ b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomActionCacheFilterAttribute.cs @@ -1,30 +1,33 @@ -//using Microsoft.AspNetCore.Mvc.Filters; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; -//namespace Zhaoxi.AgileFramework.WebCore.FilterExtend -//{ -// public class CustomActionCacheFilterAttribute : ActionFilterAttribute -// { -// public override void OnActionExecuted(ActionExecutedContext context) -// { -// context.HttpContext.Response.Headers.Add("Cache-Control", "public,max-age=6000"); -// Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnActionExecuted{this.Order}"); -// } -// public override void OnActionExecuting(ActionExecutingContext context) -// { -// Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnActionExecuting{this.Order}"); -// } -// public override void OnResultExecuting(ResultExecutingContext context) -// { -// Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnResultExecuting{this.Order}"); -// } -// public override void OnResultExecuted(ResultExecutedContext context) -// { -// Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnResultExecuted{this.Order}"); -// } -// } +namespace Yi.Framework.WebCore.FilterExtend +{ + /// + /// 缓存过滤器 + /// + public class CustomActionCacheFilterAttribute : ActionFilterAttribute + { + public override void OnActionExecuted(ActionExecutedContext context) + { + context.HttpContext.Response.Headers.Add("Cache-Control", "public,max-age=6000"); + Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnActionExecuted{this.Order}"); + } + public override void OnActionExecuting(ActionExecutingContext context) + { + Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnActionExecuting{this.Order}"); + } + public override void OnResultExecuting(ResultExecutingContext context) + { + Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnResultExecuting{this.Order}"); + } + public override void OnResultExecuted(ResultExecutedContext context) + { + Console.WriteLine($"This {nameof(CustomActionCacheFilterAttribute)} OnResultExecuted{this.Order}"); + } + } -//} +} diff --git a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomActionCheckFilterAttribute.cs b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomActionCheckFilterAttribute.cs index 05883fe9..8e255fae 100644 --- a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomActionCheckFilterAttribute.cs +++ b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomActionCheckFilterAttribute.cs @@ -1,45 +1,43 @@ -//using Microsoft.AspNetCore.Http; -//using Microsoft.AspNetCore.Mvc; -//using Microsoft.AspNetCore.Mvc.Filters; -//using Microsoft.AspNetCore.Mvc.ModelBinding; -//using Microsoft.AspNetCore.Mvc.ViewFeatures; -//using Microsoft.Extensions.Logging; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; -//namespace Zhaoxi.AgileFramework.WebCore.FilterExtend -//{ -// public class CustomActionCheckFilterAttribute : ActionFilterAttribute -// { -// #region Identity -// private readonly ILogger _logger; -// private readonly IModelMetadataProvider _modelMetadataProvider; -// public CustomActionCheckFilterAttribute(ILogger logger) -// { -// this._logger = logger; -// } -// #endregion +namespace Yi.Framework.WebCore.FilterExtend +{ + /// + /// 控制器检查过滤器 + /// + public class CustomActionCheckFilterAttribute : ActionFilterAttribute + { + #region Identity + private readonly ILogger _logger; + private readonly IModelMetadataProvider _modelMetadataProvider; + public CustomActionCheckFilterAttribute(ILogger logger) + { + this._logger = logger; + } + #endregion -// public override void OnActionExecuting(ActionExecutingContext context) -// { -// //CurrentUser currentUser = context.HttpContext.GetCurrentUserBySession(); -// //if (currentUser == null) -// //{ -// // //if (this.IsAjaxRequest(context.HttpContext.Request)) -// // //{ } -// // context.Result = new RedirectResult("~/Fourth/Login"); -// //} -// //else -// //{ -// // this._logger.LogDebug($"{currentUser.Name} 访问系统"); -// //} -// } -// private bool IsAjaxRequest(HttpRequest request) -// { -// string header = request.Headers["X-Requested-With"]; -// return "XMLHttpRequest".Equals(header); -// } -// } -//} + public override void OnActionExecuting(ActionExecutingContext context) + { + //CurrentUser currentUser = context.HttpContext.GetCurrentUserBySession(); + //if (currentUser == null) + //{ + // //if (this.IsAjaxRequest(context.HttpContext.Request)) + // //{ } + // context.Result = new RedirectResult("~/Fourth/Login"); + //} + //else + //{ + // this._logger.LogDebug($"{currentUser.Name} 访问系统"); + //} + } + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomExceptionFilterAttribute.cs b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomExceptionFilterAttribute.cs index 785a6bd6..0af7e9f8 100644 --- a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomExceptionFilterAttribute.cs +++ b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomExceptionFilterAttribute.cs @@ -8,8 +8,11 @@ using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Yi.Framework.Common.Models; -namespace CC.ElectronicCommerce.WebCore.FilterExtend +namespace Yi.Framework.WebCore.FilterExtend { + /// + /// 异常抓取过滤器 + /// public class CustomExceptionFilterAttribute : IExceptionFilter { private ILogger _logger = null; diff --git a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomIOCFilterFactoryAttribute.cs b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomIOCFilterFactoryAttribute.cs index c632c220..77a08bcf 100644 --- a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomIOCFilterFactoryAttribute.cs +++ b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomIOCFilterFactoryAttribute.cs @@ -1,31 +1,31 @@ -//using Microsoft.AspNetCore.Mvc.Filters; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; -//namespace Zhaoxi.AgileFramework.WebCore.FilterExtend -//{ -// /// -// /// 基于完成Filter的依赖注入 -// /// -// public class CustomIOCFilterFactoryAttribute : Attribute, IFilterFactory -// { -// private readonly Type _FilterType = null; +namespace Yi.Framework.WebCore.FilterExtend +{ + /// + /// 依赖注入工厂过滤器 + /// + public class CustomIOCFilterFactoryAttribute : Attribute, IFilterFactory + { + private readonly Type _FilterType = null; -// public CustomIOCFilterFactoryAttribute(Type type) -// { -// this._FilterType = type; -// } -// public bool IsReusable => true; + public CustomIOCFilterFactoryAttribute(Type type) + { + this._FilterType = type; + } + public bool IsReusable => true; -// public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) -// { -// //return (IFilterMetadata)serviceProvider.GetService(typeof(CustomExceptionFilterAttribute)); + public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) + { + //return (IFilterMetadata)serviceProvider.GetService(typeof(CustomExceptionFilterAttribute)); -// return (IFilterMetadata)serviceProvider.GetService(this._FilterType); -// } -// } + return (IFilterMetadata)serviceProvider.GetService(this._FilterType); + } + } -//} +} diff --git a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomResourceFilterAttribute.cs b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomResourceFilterAttribute.cs index 1c27eb5e..c8640ef7 100644 --- a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomResourceFilterAttribute.cs +++ b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/CustomResourceFilterAttribute.cs @@ -1,45 +1,45 @@ -//using Microsoft.AspNetCore.Mvc; -//using Microsoft.AspNetCore.Mvc.Filters; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; -//namespace Zhaoxi.AgileFramework.WebCore.FilterExtend -//{ -// /// -// /// -// /// -// public class CustomResourceFilterAttribute : Attribute, IResourceFilter, IFilterMetadata -// { -// private static Dictionary CustomCache = new Dictionary(); -// /// -// /// 发生在其他动作之前 -// /// -// /// -// public void OnResourceExecuting(ResourceExecutingContext context) -// { -// Console.WriteLine($"This is {nameof(CustomResourceFilterAttribute) }OnResourceExecuting"); -// //if 有缓存,直接返回缓存 -// string key = context.HttpContext.Request.Path; -// if (CustomCache.ContainsKey(key)) -// { -// context.Result = CustomCache[key];//断路器--到Result生成了,但是Result还需要转换成Html -// } -// } -// /// -// /// 发生在其他动作之后 -// /// -// /// -// public void OnResourceExecuted(ResourceExecutedContext context) -// { -// Console.WriteLine($"This is {nameof(CustomResourceFilterAttribute) }OnResourceExecuted"); -// //这个应该缓存起来 -// string key = context.HttpContext.Request.Path; -// if (!CustomCache.ContainsKey(key)) -// { -// CustomCache.Add(key, context.Result); -// } -// } -// } -//} +namespace Yi.Framework.WebCore.FilterExtend +{ + /// + /// 资源过滤器 + /// + public class CustomResourceFilterAttribute : Attribute, IResourceFilter, IFilterMetadata + { + private static Dictionary CustomCache = new Dictionary(); + /// + /// 发生在其他动作之前 + /// + /// + public void OnResourceExecuting(ResourceExecutingContext context) + { + Console.WriteLine($"This is {nameof(CustomResourceFilterAttribute) }OnResourceExecuting"); + //if 有缓存,直接返回缓存 + string key = context.HttpContext.Request.Path; + if (CustomCache.ContainsKey(key)) + { + context.Result = CustomCache[key];//断路器--到Result生成了,但是Result还需要转换成Html + } + } + /// + /// 发生在其他动作之后 + /// + /// + public void OnResourceExecuted(ResourceExecutedContext context) + { + Console.WriteLine($"This is {nameof(CustomResourceFilterAttribute) }OnResourceExecuted"); + //这个应该缓存起来 + string key = context.HttpContext.Request.Path; + if (!CustomCache.ContainsKey(key)) + { + CustomCache.Add(key, context.Result); + } + } + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/LogActionFilterAttribute.cs b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/LogActionFilterAttribute.cs index d07922c8..50cbca85 100644 --- a/Yi.Framework/Yi.Framework.WebCore/FilterExtend/LogActionFilterAttribute.cs +++ b/Yi.Framework/Yi.Framework.WebCore/FilterExtend/LogActionFilterAttribute.cs @@ -7,8 +7,11 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -namespace CC.ElectronicCommerce.WebCore.FilterExtend +namespace Yi.Framework.WebCore.FilterExtend { + /// + /// 日志处理过滤器 + /// public class LogActionFilterAttribute : ActionFilterAttribute { private ILogger _logger = null; diff --git a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/ConsulRegiterExtend.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs similarity index 67% rename from Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/ConsulRegiterExtend.cs rename to Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs index b38fccda..e275c04d 100644 --- a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/ConsulRegiterExtend.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ConsulRegiterExtend.cs @@ -1,44 +1,33 @@ using Consul; using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using Yi.Framework.Common.IOCOptions; -namespace CC.ElectronicCommerce.Core.ConsulExtend +namespace Yi.Framework.WebCore.MiddlewareExtend { /// /// HTTP模式 /// public static class ConsulRegiterExtend { - /// - /// 自动读取配置文件完成注册 - /// - /// - /// - /// - public static async Task UseConsulConfiguration(this IApplicationBuilder app, IConfiguration configuration) - { - ConsulRegisterOption consulRegisterOption = new ConsulRegisterOption(); - configuration.Bind("ConsulRegisterOption", consulRegisterOption); - - ConsulClientOption consulClientOption = new ConsulClientOption(); - configuration.Bind("ConsulClientOption", consulClientOption); - - await UseConsul(app, consulClientOption, consulRegisterOption); - } /// /// 基于提供信息完成注册 /// /// /// /// - public static async Task UseConsul(this IApplicationBuilder app, ConsulClientOption consulClientOption, ConsulRegisterOption consulRegisterOption) + public static async Task UseConsulService(this IApplicationBuilder app) { + var consulRegisterOption= Appsettings.app("ConsulRegisterOption"); + + var consulClientOption= Appsettings.app("ConsulRegisterOption"); using (ConsulClient client = new ConsulClient(c => { c.Address = new Uri($"http://{consulClientOption.IP}:{consulClientOption.Port}/"); diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/CorsExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/CorsExtension.cs new file mode 100644 index 00000000..c5d8827a --- /dev/null +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/CorsExtension.cs @@ -0,0 +1,34 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.OpenApi.Models; +using System; +using System.IO; + +namespace Yi.Framework.WebCore.MiddlewareExtend +{ + /// + /// 通用跨域扩展 + /// + public static class CorsExtension + { + public static IServiceCollection AddCorsService(this IServiceCollection services) + { + services.AddCors(options => options.AddPolicy("CorsPolicy",//解决跨域问题 + builder => + { + builder.AllowAnyMethod() + .SetIsOriginAllowed(_ => true) + .AllowAnyHeader() + .AllowCredentials(); + })); + + return services; + } + + public static void UseCorsService(this IApplicationBuilder app) + { + app.UseCors("CorsPolicy"); + } + + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DataBaseExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DataBaseExtension.cs new file mode 100644 index 00000000..3a29a6eb --- /dev/null +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/DataBaseExtension.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.OpenApi.Models; +using System; +using System.IO; +using Yi.Framework.Common.IOCOptions; + +namespace Yi.Framework.WebCore.MiddlewareExtend +{ + /// + /// 数据库扩展 + /// + public static class DataBaseExtension + { + public static IServiceCollection AddDataBaseService(this IServiceCollection services , string appsettings) + { + Appsettings.app(appsettings); + return services; + } + + public static void UseDataBaseService(this IApplicationBuilder app) + { + + } + + } +} diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ErrorHandExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ErrorHandExtension.cs new file mode 100644 index 00000000..20ca07c2 --- /dev/null +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/ErrorHandExtension.cs @@ -0,0 +1,75 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Yi.Framework.Common.Models; + +namespace Yi.Framework.WebCore.MiddlewareExtend +{ + /// + /// 异常抓取反馈扩展 + /// + public class ErrorHandExtension + { + private readonly RequestDelegate next; + + public ErrorHandExtension(RequestDelegate next) + { + this.next = next; + } + + public async Task Invoke(HttpContext context) + { + try + { + await next(context); + } + catch (Exception ex) + { + var statusCode = context.Response.StatusCode; + if (ex is ArgumentException) + { + statusCode = 200; + } + await HandleExceptionAsync(context, statusCode, ex.Message); + } + finally + { + var statusCode = context.Response.StatusCode; + var msg = ""; + + switch (statusCode) + { + + case 401: msg = "未授权";break; + case 403: msg = "未授权"; break; + case 404: msg = "未找到服务"; break; + case 502: msg = "请求错误"; break; + + } + if (!string.IsNullOrWhiteSpace(msg)) + { + await HandleExceptionAsync(context, statusCode, msg); + } + } + } + //异常错误信息捕获,将错误信息用Json方式返回 + private static Task HandleExceptionAsync(HttpContext context, int statusCode, string msg) + { + var result = JsonConvert.SerializeObject( Result.Error(msg).SetCode(statusCode)); + context.Response.ContentType = "application/json;charset=utf-8"; + return context.Response.WriteAsync(result); + } + } + //扩展方法 + public static class ErrorHandlingExtensions + { + public static IApplicationBuilder UseErrorHandling(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } + } +} \ No newline at end of file diff --git a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/HealthCheckMiddleware.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/HealthCheckExtension.cs similarity index 84% rename from Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/HealthCheckMiddleware.cs rename to Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/HealthCheckExtension.cs index b952fef1..7c49c1bd 100644 --- a/Yi.Framework/Yi.Framework.Core/ConsulExtend/ServerExtend/HealthCheckMiddleware.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/HealthCheckExtension.cs @@ -7,9 +7,12 @@ using System.Net; using System.Text; using System.Threading.Tasks; -namespace CC.ElectronicCommerce.Core.ConsulExtend +namespace Yi.Framework.WebCore.MiddlewareExtend { - public static class HealthCheckMiddleware + /// + /// 健康检测扩展 + /// + public static class HealthCheckExtension { /// /// 设置心跳响应 diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/PreOptionRequestMiddleware.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/PreOptionRequestExtension.cs similarity index 63% rename from Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/PreOptionRequestMiddleware.cs rename to Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/PreOptionRequestExtension.cs index 2a59d52c..c8d4a251 100644 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/PreOptionRequestMiddleware.cs +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/PreOptionRequestExtension.cs @@ -5,18 +5,16 @@ using System.Collections.Generic; using System.Text; using System.Threading.Tasks; -namespace CC.ElectronicCommerce.WebCore.MiddlewareExtend +namespace Yi.Framework.WebCore.MiddlewareExtend { /// - /// Axios会触发,需要做个状态返回,还需要指定跨域信息,这里放在网关了 - /// - /// OPTIONS请求即预检请求,可用于检测服务器允许的http方法。当发起跨域请求时,由于安全原因,触发一定条件时浏览器会在正式请求之前自动先发起OPTIONS请求,即CORS预检请求,服务器若接受该跨域请求,浏览器才继续发起正式请求。 + /// 预检请求扩展 /// - public class PreOptionRequestMiddleware + public class PreOptionRequestExtension { private readonly RequestDelegate _next; - public PreOptionRequestMiddleware(RequestDelegate next) + public PreOptionRequestExtension(RequestDelegate next) { _next = next; } @@ -42,7 +40,7 @@ namespace CC.ElectronicCommerce.WebCore.MiddlewareExtend { public static IApplicationBuilder UsePreOptionsRequest(this IApplicationBuilder app) { - return app.UseMiddleware(); + return app.UseMiddleware(); } } diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/StaticPageExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/StaticPageExtension.cs new file mode 100644 index 00000000..429fdce7 --- /dev/null +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/StaticPageExtension.cs @@ -0,0 +1,156 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Yi.Framework.WebCore.MiddlewareExtend +{ + /// + /// 静态化页面处理扩展 + /// + public class StaticPageExtension + { + private readonly RequestDelegate _next; + private string _directoryPath = @"D:/cc-yi/"; + private bool _supportDelete = false; + private bool _supportWarmup = false; + + public StaticPageExtension(RequestDelegate next, string directoryPath, bool supportDelete, bool supportWarmup) + { + this._next = next; + this._directoryPath = directoryPath; + this._supportDelete = supportDelete; + this._supportWarmup = supportWarmup; + } + + public async Task InvokeAsync(HttpContext context) + { + if (this._supportDelete && "Delete".Equals(context.Request.Query["ActionHeader"])) + { + this.DeleteHmtl(context.Request.Path.Value); + context.Response.StatusCode = 200; + } + else if (this._supportWarmup && "ClearAll".Equals(context.Request.Query["ActionHeader"])) + { + this.ClearDirectory(10);//考虑数据量 + context.Response.StatusCode = 200; + } + else if (!context.Request.IsAjaxRequest()) + { + Console.WriteLine($"This is StaticPageMiddleware InvokeAsync {context.Request.Path.Value}"); + #region context.Response.Body + var originalStream = context.Response.Body; + using (var copyStream = new MemoryStream()) + { + context.Response.Body = copyStream; + await _next(context); + + copyStream.Position = 0; + var reader = new StreamReader(copyStream); + var content = await reader.ReadToEndAsync(); + string url = context.Request.Path.Value; + + this.SaveHmtl(url, content); + + copyStream.Position = 0; + await copyStream.CopyToAsync(originalStream); + context.Response.Body = originalStream; + } + #endregion + } + else + { + await _next(context); + } + } + + private void SaveHmtl(string url, string html) + { + try + { + //Console.WriteLine($"Response: {html}"); + if (string.IsNullOrWhiteSpace(html)) + return; + if (!url.EndsWith(".html")) + return; + + if (Directory.Exists(_directoryPath) == false) + Directory.CreateDirectory(_directoryPath); + + var totalPath = Path.Combine(_directoryPath, url.Split("/").Last()); + File.WriteAllText(totalPath, html);//直接覆盖 + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + /// + /// 删除某个页面 + /// + /// + /// + private void DeleteHmtl(string url) + { + try + { + if (!url.EndsWith(".html")) + return; + var totalPath = Path.Combine(_directoryPath, url.Split("/").Last()); + File.Delete(totalPath);//直接删除 + } + catch (Exception ex) + { + Console.WriteLine($"Delete {url} 异常,{ex.Message}"); + } + } + + /// + /// 清理文件,支持重试 + /// + /// 最多重试次数 + private void ClearDirectory(int index) + { + if (index > 0)//简陋版---重试index次 + { + try + { + var files = Directory.GetFiles(_directoryPath); + foreach (var file in files) + { + File.Delete(file); + } + } + catch (Exception ex) + { + Console.WriteLine($"ClearDirectory failed {ex.Message}"); + ClearDirectory(index--); + } + } + } + } + + /// + /// 扩展中间件 + /// + public static class StaticPageMiddlewareExtensions + { + /// + /// + /// + /// + /// 文件写入地址,文件夹目录 + /// 是否支持删除 + /// 是否支持全量删除 + /// + public static IApplicationBuilder UseStaticPageMiddleware(this IApplicationBuilder app, string directoryPath, bool supportDelete, bool supportClear) + { + return app.UseMiddleware(directoryPath, supportDelete, supportClear); + } + } +} \ No newline at end of file diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/StaticPageMiddleware.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/StaticPageMiddleware.cs deleted file mode 100644 index c9340eef..00000000 --- a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/StaticPageMiddleware.cs +++ /dev/null @@ -1,156 +0,0 @@ -//using Microsoft.AspNetCore.Builder; -//using Microsoft.AspNetCore.Http; -//using System; -//using System.Collections.Generic; -//using System.IO; -//using System.Linq; -//using System.Text; -//using System.Threading.Tasks; - -//namespace CC.ElectronicCommerce.WebCore.MiddlewareExtend -//{ -// /// -// /// 支持在返回HTML时,将返回的Stream保存到指定目录 -// /// -// public class StaticPageMiddleware -// { -// private readonly RequestDelegate _next; -// private string _directoryPath = @"D:/cc-ec/"; -// private bool _supportDelete = false; -// private bool _supportWarmup = false; - -// public StaticPageMiddleware(RequestDelegate next, string directoryPath, bool supportDelete, bool supportWarmup) -// { -// this._next = next; -// this._directoryPath = directoryPath; -// this._supportDelete = supportDelete; -// this._supportWarmup = supportWarmup; -// } - -// public async Task InvokeAsync(HttpContext context) -// { -// if (this._supportDelete && "Delete".Equals(context.Request.Query["ActionHeader"])) -// { -// this.DeleteHmtl(context.Request.Path.Value); -// context.Response.StatusCode = 200; -// } -// else if (this._supportWarmup && "ClearAll".Equals(context.Request.Query["ActionHeader"])) -// { -// this.ClearDirectory(10);//考虑数据量 -// context.Response.StatusCode = 200; -// } -// else if (!context.Request.IsAjaxRequest()) -// { -// Console.WriteLine($"This is StaticPageMiddleware InvokeAsync {context.Request.Path.Value}"); -// #region context.Response.Body -// var originalStream = context.Response.Body; -// using (var copyStream = new MemoryStream()) -// { -// context.Response.Body = copyStream; -// await _next(context); - -// copyStream.Position = 0; -// var reader = new StreamReader(copyStream); -// var content = await reader.ReadToEndAsync(); -// string url = context.Request.Path.Value; - -// this.SaveHmtl(url, content); - -// copyStream.Position = 0; -// await copyStream.CopyToAsync(originalStream); -// context.Response.Body = originalStream; -// } -// #endregion -// } -// else -// { -// await _next(context); -// } -// } - -// private void SaveHmtl(string url, string html) -// { -// try -// { -// //Console.WriteLine($"Response: {html}"); -// if (string.IsNullOrWhiteSpace(html)) -// return; -// if (!url.EndsWith(".html")) -// return; - -// if (Directory.Exists(_directoryPath) == false) -// Directory.CreateDirectory(_directoryPath); - -// var totalPath = Path.Combine(_directoryPath, url.Split("/").Last()); -// File.WriteAllText(totalPath, html);//直接覆盖 -// } -// catch (Exception ex) -// { -// Console.WriteLine(ex.Message); -// } -// } - -// /// -// /// 删除某个页面 -// /// -// /// -// /// -// private void DeleteHmtl(string url) -// { -// try -// { -// if (!url.EndsWith(".html")) -// return; -// var totalPath = Path.Combine(_directoryPath, url.Split("/").Last()); -// File.Delete(totalPath);//直接删除 -// } -// catch (Exception ex) -// { -// Console.WriteLine($"Delete {url} 异常,{ex.Message}"); -// } -// } - -// /// -// /// 清理文件,支持重试 -// /// -// /// 最多重试次数 -// private void ClearDirectory(int index) -// { -// if (index > 0)//简陋版---重试index次 -// { -// try -// { -// var files = Directory.GetFiles(_directoryPath); -// foreach (var file in files) -// { -// File.Delete(file); -// } -// } -// catch (Exception ex) -// { -// Console.WriteLine($"ClearDirectory failed {ex.Message}"); -// ClearDirectory(index--); -// } -// } -// } -// } - -// /// -// /// 扩展中间件 -// /// -// public static class StaticPageMiddlewareExtensions -// { -// /// -// /// -// /// -// /// -// /// 文件写入地址,文件夹目录 -// /// 是否支持删除 -// /// 是否支持全量删除 -// /// -// public static IApplicationBuilder UseStaticPageMiddleware(this IApplicationBuilder app, string directoryPath, bool supportDelete, bool supportClear) -// { -// return app.UseMiddleware(directoryPath, supportDelete, supportClear); -// } -// } -//} \ No newline at end of file diff --git a/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/SwaggerExtension.cs b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/SwaggerExtension.cs new file mode 100644 index 00000000..e0802d84 --- /dev/null +++ b/Yi.Framework/Yi.Framework.WebCore/MiddlewareExtend/SwaggerExtension.cs @@ -0,0 +1,76 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.OpenApi.Models; +using System; +using System.IO; + +namespace Yi.Framework.WebCore.MiddlewareExtend +{ + /// + /// Swagger扩展 + /// + public static class SwaggerExtension + { + public static IServiceCollection AddSwaggerService(this IServiceCollection services) + { + var apiInfo = new OpenApiInfo + { + Title = "Yi意框架-API接口", + Version = "v1", + Contact = new OpenApiContact { Name = "橙子", Email = "454313500@qq.com", Url = new System.Uri("https://ccnetcore.com") } + }; + #region 注册Swagger服务 + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", apiInfo); + + //添加注释服务 + //为 Swagger JSON and UI设置xml文档注释路径 + //获取应用程序所在目录(绝对路径,不受工作目录影响,建议采用此方法获取路径使用windwos&Linux) + var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); + var apiXmlPath = Path.Combine(basePath, @"ApiDoc.xml");//控制器层注释 + var entityXmlPath = Path.Combine(basePath, @"SwaggerDoc.xml");//实体注释 + //c.IncludeXmlComments(apiXmlPath, true);//true表示显示控制器注释 + c.IncludeXmlComments(entityXmlPath); + + //添加控制器注释 + //c.DocumentFilter(); + + //添加header验证信息 + //c.OperationFilter(); + //var security = new Dictionary> { { "Bearer", new string[] { } }, }; + + c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() + { + Description = "文本框里输入从服务器获取的Token。格式为:Bearer + 空格+token",//JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\" + Name = "Authorization",////jwt默认的参数名称 + In = ParameterLocation.Header,////jwt默认存放Authorization信息的位置(请求头中) + Type = SecuritySchemeType.ApiKey, + }); + c.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { new OpenApiSecurityScheme + { + Reference = new OpenApiReference() + { + Id = "Bearer", + Type = ReferenceType.SecurityScheme + } + }, Array.Empty() } + }); + }); + #endregion + + return services; + } + + public static void UseSwaggerService(this IApplicationBuilder app) + { + //在 Startup.Configure 方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务: + // Enable middleware to serve generated Swagger as a JSON endpoint. + app.UseSwagger(); + app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Yi.Framework")); + } + + } +}