提交.Net6版本
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
using DotNetCore.CAP.Dashboard.NodeDiscovery;
|
||||
using DotNetCore.CAP.Messages;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
public static class CAPExtend
|
||||
{
|
||||
public static IServiceCollection AddCAPService<T>(this IServiceCollection services)
|
||||
{
|
||||
if (Appsettings.appBool("CAP_Enabled"))
|
||||
{
|
||||
services.AddCap(x =>
|
||||
{
|
||||
x.UseMySql(Appsettings.app("DbConn", "WriteUrl"));
|
||||
|
||||
x.UseRabbitMQ(optios => {
|
||||
optios.HostName = Appsettings.app("RabbitConn", "HostName");
|
||||
optios.Port =Convert.ToInt32(Appsettings.app("RabbitConn", "Port"));
|
||||
optios.UserName = Appsettings.app("RabbitConn", "UserName");
|
||||
optios.Password = Appsettings.app("RabbitConn", "Password");
|
||||
|
||||
});
|
||||
x.FailedRetryCount = 30;
|
||||
x.FailedRetryInterval = 60;//second
|
||||
x.FailedThresholdCallback = failed =>
|
||||
{
|
||||
var logger = failed.ServiceProvider.GetService<ILogger<T>>();
|
||||
logger.LogError($@"MessageType {failed.MessageType} 失败了, 重试了 {x.FailedRetryCount} 次,
|
||||
消息名称: {failed.Message.GetName()}");//do anything
|
||||
};
|
||||
if (Appsettings.appBool("CAPDashboard_Enabled"))
|
||||
{
|
||||
x.UseDashboard();
|
||||
var discoveryOptions = Appsettings.app<DiscoveryOptions>();
|
||||
x.UseDiscovery(d =>
|
||||
{
|
||||
d.DiscoveryServerHostName = discoveryOptions.DiscoveryServerHostName;
|
||||
d.DiscoveryServerPort = discoveryOptions.DiscoveryServerPort;
|
||||
d.CurrentNodeHostName = discoveryOptions.CurrentNodeHostName;
|
||||
d.CurrentNodePort = discoveryOptions.CurrentNodePort;
|
||||
d.NodeId = discoveryOptions.NodeId;
|
||||
d.NodeName = discoveryOptions.NodeName;
|
||||
d.MatchPath = discoveryOptions.MatchPath;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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 Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// HTTP模式
|
||||
/// </summary>
|
||||
public static class ConsulRegiterExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 基于提供信息完成注册
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
/// <param name="healthService"></param>
|
||||
/// <returns></returns>
|
||||
public static void UseConsulService(this IApplicationBuilder app)
|
||||
{
|
||||
|
||||
if (Appsettings.appBool("Consul_Enabled"))
|
||||
{
|
||||
var consulRegisterOption = Appsettings.app<ConsulRegisterOption>("ConsulRegisterOption");
|
||||
|
||||
var consulClientOption = Appsettings.app<ConsulClientOption>("ConsulClientOption");
|
||||
using (ConsulClient client = new ConsulClient(c =>
|
||||
{
|
||||
c.Address = new Uri($"http://{consulClientOption.IP}:{consulClientOption.Port}/");
|
||||
c.Datacenter = consulClientOption.Datacenter;
|
||||
}))
|
||||
{
|
||||
client.Agent.ServiceRegister(new AgentServiceRegistration()
|
||||
{
|
||||
ID = $"{consulRegisterOption.IP}-{consulRegisterOption.Port}-{Guid.NewGuid()}",//唯一Id
|
||||
Name = consulRegisterOption.GroupName,//组名称-Group
|
||||
Address = consulRegisterOption.IP,
|
||||
Port = consulRegisterOption.Port,
|
||||
Tags = new string[] { consulRegisterOption.Tag },
|
||||
Check = new AgentServiceCheck()
|
||||
{
|
||||
Interval = TimeSpan.FromSeconds(consulRegisterOption.Interval),
|
||||
HTTP = $"http://{consulRegisterOption.IP}:{consulRegisterOption.Port}{consulRegisterOption.HealthCheckUrl}",
|
||||
Timeout = TimeSpan.FromSeconds(consulRegisterOption.Timeout),
|
||||
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(consulRegisterOption.DeregisterCriticalServiceAfter)
|
||||
}
|
||||
}).Wait();
|
||||
Console.WriteLine($"{JsonConvert.SerializeObject(consulRegisterOption)} 完成注册");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 通用跨域扩展
|
||||
/// </summary>
|
||||
public static class CorsExtension
|
||||
{
|
||||
public static IServiceCollection AddCorsService(this IServiceCollection services)
|
||||
{
|
||||
|
||||
if (Appsettings.appBool("Cors_Enabled"))
|
||||
{
|
||||
services.AddCors(options => options.AddPolicy("CorsPolicy",//解决跨域问题
|
||||
builder =>
|
||||
{
|
||||
builder.AllowAnyMethod()
|
||||
.SetIsOriginAllowed(_ => true)
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials();
|
||||
}));
|
||||
}
|
||||
return services;
|
||||
}
|
||||
|
||||
public static void UseCorsService(this IApplicationBuilder app)
|
||||
{
|
||||
if (Appsettings.appBool("Cors_Enabled"))
|
||||
{
|
||||
app.UseCors("CorsPolicy");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
using Yi.Framework.Model;
|
||||
using Yi.Framework.Model.ModelFactory;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
public static class DbExtend
|
||||
{
|
||||
public static IServiceCollection AddDbService(this IServiceCollection services)
|
||||
{
|
||||
DbContextFactory.MutiDB_Enabled = Appsettings.appBool("MutiDB_Enabled");
|
||||
DataContext.DbSelect = Appsettings.app("DbSelect");
|
||||
DataContext._connStr = Appsettings.app("DbConn", "WriteUrl");
|
||||
services.Configure<DbConnOptions>(Appsettings.appConfiguration("DbConn"));
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using log4net;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Model.ModelFactory;
|
||||
using Yi.Framework.WebCore.Init;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
public static class DbSeedInitExtend
|
||||
{
|
||||
private static readonly ILog log = LogManager.GetLogger(typeof(DbSeedInitExtend));
|
||||
public static void UseDbSeedInitService(this IApplicationBuilder app, IDbContextFactory _DbFactory)
|
||||
{
|
||||
|
||||
if (Appsettings.appBool("DbSeed_Enabled"))
|
||||
{
|
||||
if (app == null) throw new ArgumentNullException(nameof(app));
|
||||
|
||||
try
|
||||
{
|
||||
DataSeed.SeedAsync(_DbFactory).Wait();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.Error($"Error occured seeding the Database.\n{e.Message}");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
using Yi.Framework.Core;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// Redis扩展
|
||||
/// </summary>
|
||||
public static class ElasticSeachExtend
|
||||
{
|
||||
public static IServiceCollection AddElasticSeachService(this IServiceCollection services)
|
||||
{
|
||||
if (Appsettings.appBool("ElasticSeach_Enabled"))
|
||||
{
|
||||
services.Configure<ElasticSearchOptions>(Appsettings.appConfiguration("ElasticSeachConn"));
|
||||
services.AddTransient<ElasticSearchInvoker>();
|
||||
}
|
||||
return services;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
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
|
||||
{
|
||||
/// <summary>
|
||||
/// 异常抓取反馈扩展
|
||||
/// </summary>
|
||||
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)
|
||||
{
|
||||
Result resp;
|
||||
if (statusCode == 401)
|
||||
{
|
||||
resp = Result.UnAuthorize(msg);
|
||||
}
|
||||
else
|
||||
{
|
||||
resp = Result.Error(msg);
|
||||
}
|
||||
var result = JsonConvert.SerializeObject(resp);
|
||||
context.Response.ContentType = "application/json;charset=utf-8";
|
||||
return context.Response.WriteAsync(result);
|
||||
}
|
||||
}
|
||||
//扩展方法
|
||||
public static class ErrorHandlingExtensions
|
||||
{
|
||||
public static IApplicationBuilder UseErrorHandlingService(this IApplicationBuilder builder)
|
||||
{
|
||||
return builder.UseMiddleware<ErrorHandExtension>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 健康检测扩展
|
||||
/// </summary>
|
||||
public static class HealthCheckExtension
|
||||
{
|
||||
/// <summary>
|
||||
/// 设置心跳响应
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
/// <param name="checkPath">默认是/Health</param>
|
||||
/// <returns></returns>
|
||||
public static void UseHealthCheckMiddleware(this IApplicationBuilder app, string checkPath = "/Health")
|
||||
{
|
||||
if (Appsettings.appBool("HealthCheck_Enabled"))
|
||||
{
|
||||
app.Map(checkPath, applicationBuilder => applicationBuilder.Run(async context =>
|
||||
{
|
||||
Console.WriteLine($"This is Health Check");
|
||||
context.Response.StatusCode = (int)HttpStatusCode.OK;
|
||||
await context.Response.WriteAsync("OK");
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.IO;
|
||||
using Yi.Framework.Model;
|
||||
using Yi.Framework.Model.ModelFactory;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 通用跨域扩展
|
||||
/// </summary>
|
||||
public static class IocExtension
|
||||
{
|
||||
public static IServiceCollection AddIocService(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
#region
|
||||
//配置文件使用配置
|
||||
#endregion
|
||||
services.AddSingleton(new Appsettings(configuration));
|
||||
#region
|
||||
//数据库配置
|
||||
#endregion
|
||||
services.AddTransient<DbContext, DataContext>();
|
||||
return services;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Yi.Framework.Common.Const;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 通用跨域扩展
|
||||
/// </summary>
|
||||
public static class JwtExtension
|
||||
{
|
||||
public static IServiceCollection AddJwtService(this IServiceCollection services)
|
||||
{
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,//是否验证Issuer
|
||||
ValidateAudience = true,//是否验证Audience
|
||||
ValidateLifetime = true,//是否验证失效时间
|
||||
ClockSkew = TimeSpan.FromDays(1),
|
||||
|
||||
ValidateIssuerSigningKey = true,//是否验证SecurityKey
|
||||
ValidAudience = JwtConst.Domain,//Audience
|
||||
ValidIssuer = JwtConst.Domain,//Issuer,这两项和前面签发jwt的设置一致
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtConst.SecurityKey))//拿到SecurityKey
|
||||
};
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 预检请求扩展
|
||||
/// </summary>
|
||||
public class PreOptionRequestExtension
|
||||
{
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
public PreOptionRequestExtension(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
if (context.Request.Method.ToUpper() == "OPTIONS")
|
||||
{
|
||||
//context.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:8070");
|
||||
//context.Response.Headers.Add("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH,OPTIONS");
|
||||
//context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
|
||||
context.Response.StatusCode = 200;
|
||||
return;
|
||||
}
|
||||
await _next.Invoke(context);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扩展中间件
|
||||
/// </summary>
|
||||
public static class PreOptionsRequestMiddlewareExtensions
|
||||
{
|
||||
public static IApplicationBuilder UsePreOptionsRequest(this IApplicationBuilder app)
|
||||
{
|
||||
return app.UseMiddleware<PreOptionRequestExtension>();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using Autofac.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Quartz;
|
||||
using Quartz.Impl;
|
||||
using Quartz.Spi;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Core;
|
||||
using Yi.Framework.Core.Quartz;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// 启动定时器服务,后台服务
|
||||
/// </summary>
|
||||
public static class QuartzExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用定时器
|
||||
/// </summary>
|
||||
/// <param name="services"></param>
|
||||
/// <returns></returns>
|
||||
public static IServiceCollection AddQuartzService(this IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<QuartzInvoker>();
|
||||
services.AddSingleton<IJobFactory, MyQuartzFactory>();
|
||||
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
|
||||
return services;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
using Yi.Framework.Core;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// Redis扩展
|
||||
/// </summary>
|
||||
public static class RabbitMQExtension
|
||||
{
|
||||
public static IServiceCollection AddRabbitMQService(this IServiceCollection services)
|
||||
{
|
||||
if (Appsettings.appBool("RabbitMQ_Enabled"))
|
||||
{
|
||||
services.Configure<RabbitMQOptions>(Appsettings.appConfiguration("RabbitConn"));
|
||||
services.AddTransient<RabbitMQInvoker>();
|
||||
}
|
||||
return services;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System;
|
||||
using System.IO;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
using Yi.Framework.Core;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// Redis扩展
|
||||
/// </summary>
|
||||
public static class RedisExtension
|
||||
{
|
||||
public static IServiceCollection AddRedisService(this IServiceCollection services)
|
||||
{
|
||||
if (Appsettings.appBool("Redis_Enabled"))
|
||||
{
|
||||
services.Configure<RedisConnOptions>(Appsettings.appConfiguration("RedisConnOptions"));
|
||||
services.AddTransient<CacheClientDB>();
|
||||
}
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using log4net;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Yi.Framework.Core;
|
||||
using Yi.Framework.Model.ModelFactory;
|
||||
using Yi.Framework.WebCore.Init;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
public static class RedisInitExtend
|
||||
{
|
||||
private static readonly ILog log = LogManager.GetLogger(typeof(RedisInitExtend));
|
||||
public static void UseRedisSeedInitService(this IApplicationBuilder app, CacheClientDB _cacheClientDB)
|
||||
{
|
||||
|
||||
if (Appsettings.appBool("RedisSeed_Enabled"))
|
||||
{
|
||||
if (app == null) throw new ArgumentNullException(nameof(app));
|
||||
|
||||
try
|
||||
{
|
||||
RedisInit.Seed(_cacheClientDB);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
log.Error($"Error occured seeding the RedisInit.\n{e.Message}");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System;
|
||||
using System.IO;
|
||||
using Yi.Framework.Common.IOCOptions;
|
||||
using Yi.Framework.Core;
|
||||
using Yi.Framework.Core.SMS;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// Redis扩展
|
||||
/// </summary>
|
||||
public static class SMSExtension
|
||||
{
|
||||
public static IServiceCollection AddSMSService(this IServiceCollection services)
|
||||
{
|
||||
if (Appsettings.appBool("SMS_Enabled"))
|
||||
{
|
||||
|
||||
services.Configure<SMSOptions>(Appsettings.appConfiguration("SMS"));
|
||||
services.AddTransient<AliyunSMSInvoker>();
|
||||
}
|
||||
return services;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 静态化页面处理扩展
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除某个页面
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <param name="index"></param>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清理文件,支持重试
|
||||
/// </summary>
|
||||
/// <param name="index">最多重试次数</param>
|
||||
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--);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扩展中间件
|
||||
/// </summary>
|
||||
public static class StaticPageMiddlewareExtensions
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="app"></param>
|
||||
/// <param name="directoryPath">文件写入地址,文件夹目录</param>
|
||||
/// <param name="supportDelete">是否支持删除</param>
|
||||
/// <param name="supportClear">是否支持全量删除</param>
|
||||
/// <returns></returns>
|
||||
public static IApplicationBuilder UseStaticPageMiddleware(this IApplicationBuilder app, string directoryPath, bool supportDelete, bool supportClear)
|
||||
{
|
||||
return app.UseMiddleware<StaticPageExtension>(directoryPath, supportDelete, supportClear);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
using IGeekFan.AspNetCore.Knife4jUI;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using System;
|
||||
using System.IO;
|
||||
using Yi.Framework.Common.Models;
|
||||
|
||||
namespace Yi.Framework.WebCore.MiddlewareExtend
|
||||
{
|
||||
/// <summary>
|
||||
/// Swagger扩展
|
||||
/// </summary>
|
||||
public static class SwaggerExtension
|
||||
{
|
||||
public static IServiceCollection AddSwaggerService<Program>(this IServiceCollection services, string title = "Yi意框架-API接口")
|
||||
{
|
||||
var apiInfo = new OpenApiInfo
|
||||
{
|
||||
Title = title,
|
||||
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, @"SwaggerDoc.xml");//控制器层注释
|
||||
//var entityXmlPath = Path.Combine(basePath, @"SwaggerDoc.xml");//实体注释
|
||||
//c.IncludeXmlComments(apiXmlPath, true);//true表示显示控制器注释
|
||||
c.IncludeXmlComments(apiXmlPath,true);
|
||||
|
||||
//添加控制器注释
|
||||
//c.DocumentFilter<SwaggerDocTag>();
|
||||
|
||||
//添加header验证信息
|
||||
//c.OperationFilter<SwaggerHeader>();
|
||||
//var security = new Dictionary<string, IEnumerable<string>> { { "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<string>() }
|
||||
});
|
||||
|
||||
c.AddServer(new OpenApiServer()
|
||||
{
|
||||
Url = "https://ccnetcore.com",
|
||||
Description = "Yi-Framework"
|
||||
});
|
||||
c.CustomOperationIds(apiDesc =>
|
||||
{
|
||||
var controllerAction = apiDesc.ActionDescriptor as ControllerActionDescriptor;
|
||||
return controllerAction.ActionName;
|
||||
});
|
||||
});
|
||||
#endregion
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static void UseSwaggerService(this IApplicationBuilder app, params SwaggerModel[] swaggerModels)
|
||||
{
|
||||
//在 Startup.Configure 方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:
|
||||
// Enable middleware to serve generated Swagger as a JSON endpoint.
|
||||
app.UseSwagger();
|
||||
|
||||
|
||||
app.UseKnife4UI(c =>
|
||||
{
|
||||
c.RoutePrefix = "swagger"; // serve the UI at root
|
||||
if (swaggerModels.Length == 0)
|
||||
{
|
||||
c.SwaggerEndpoint("/v1/swagger.json", "Yi.Framework");
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var k in swaggerModels)
|
||||
{
|
||||
c.SwaggerEndpoint(k.url, k.name);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
//app.UseSwaggerUI(c =>
|
||||
//{
|
||||
// if (swaggerModels.Length == 0)
|
||||
// {
|
||||
// c.SwaggerEndpoint("/swagger/v1/swagger.json", "Yi.Framework");
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// foreach (var k in swaggerModels)
|
||||
// {
|
||||
// c.SwaggerEndpoint(k.url, k.name);
|
||||
// }
|
||||
// }
|
||||
|
||||
//}
|
||||
|
||||
//);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user