services.AddSingleton<DesService, DesService>();
//sql调试使用 结合 operation:analysisDebug 和 operation:sqlDebug
// "sqlDebug": true, //数据库sql调试, operation
//"analysisDebug": true //性能调试
services.AddSingleton<IDebugProvider, DebugProvider>();
//添加本地注入服务
services.AddLocalService(); ;
services.AddDatabaseFeature();
services.AddSqlServerBatcherProvider();
services.AddMySqlBatcherProvider();
services.AddSqliteBatcherProvider();
services.AddOracleBatcherProvider();
services.AddPostgreSQLBatcherProvider();
services.AddSinoregalBatcherProvider();
services.AddSingleton<IConfigurationBuilderProvider, ConfigurationBuilderProvider>();
services.AddSingleton<IDbContext, DbContext>();
services.AddXmlMapperProvider();
//services.AddSingleton<IMapperProvider, XmlMapperProvider>();
//services.AddSingleton<IMapperProvider, JsonMapperProvider>();
//注入操作日志记录
services.AddSingleton<IOperateLog, BO.DB.Providers.OperateLogProvider>();
//文件操作
services.AddSingleton<IGuid, GuidRepository>();
services.AddSingleton<IFileAndImage, FileAndImageProvider>();
//使用Scoped方式为了调用 内置的其它服务
//services.AddScoped<ILoginProvider, LoginProvider>();
//services.AddScoped<ISingleLoginProvider, SingleLoginProvider>();
services.AddSingleton<ILoginProvider, LoginProvider>();
services.AddSingleton<ISingleLoginProvider, SingleLoginProvider>();
services.AddSingleton<ISaveExtendProvider, SaveExtendProvider>();
//RG3.BO.Qu mapper里面接口参数预处理,用于需要用到第三方接口数据作为参数 扩展
//使用时候 实现 IParamsPresetProvider 接口,并替换 ParamsPresetProvider
services.AddSingleton<IParamsPresetProvider, ParamsPresetProvider>();
//创建 token等信息
services.AddSingleton<IAuthProvider, AuthProvider>();
//权限信息
services.AddSingleton<IPopedomProvider, PopedomProvider>();
//services.AddSingleton<IConfigurationBuilderProvider, IConfigurationBuilderProvider>();
services.AddSingleton<IQuDataResultCache, QuDataResultProvider>();
services.AddSingleton<IDataBizCache, DataBizCacheProvider>();
//mapper 用户行为 未实现
services.AddSingleton<IUserBehaviorProvider, UserBehaviorProvider>();
//用户日志
services.AddSingleton<IUserLogProvider, UserLogProvider>();
//用户token 使用 IAuthProvider
//services.AddSingleton<IUserTokenProvider, UserTokenProvider>();
//订阅实现
services.AddSingleton<ISubPush, SubPushProvider>();
//基础数据 文件变更订阅和存储 未实现
services.AddSingleton<ISubPushBasis, SubPushBasisProvider>();
//维数据 文件变更订阅和存储 未实现
services.AddSingleton<ISubPushDimData, SubPushDimDataProvider>();
//bridge文件变更订阅和存储 未实现
services.AddSingleton<ISubPushBridge, SubPushBridgeProvider>();
//mapper 文件变更订阅和存储 未实现
services.AddSingleton<ISubPushMapper, SubPushMapperProvider>();
//消息推送 和订阅
//services.AddSingleton<ISubscribePublish, SubscribePublishProvider>();
services.AddRedisMQ(_configuration, null, 8);
//添加自定义缓存
services.AddMemoryCustomizeCache(_configuration);
using JasonSoft.Net.JsHttpClient.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
//using Microsoft.AspNetCore.SpaServices.Extensions;
using Newtonsoft.Json.Serialization;
using RG3.DO.Abstractions.Interfaces;
using RG3.DO.Core;
using RG3.DO.Mapper.Json;
using RG3.DO.Mapper.Xml;
//using RG3.DO.Mapper.Xml;
using RG3.DO.SqlServer;
using RG3.PF.Abstractions.Consts;
using RG3.PF.Abstractions.Entity;
using RG3.PF.Abstractions.Extensions;
using RG3.PF.Abstractions.Interfaces;
using RG3.PF.Caching.Memcached.Extensions;
using RG3.PF.Utilities;
using RG3.PF.Utilities.Extensions;
using RG3.PF.Utilities.Providers;
using RG3.PF.Utilities.Services;
using System.Collections.Generic;
using System.Net.Http;
using RG3.PF.Utilities.Repository;
using Microsoft.AspNetCore.CookiePolicy;
using Ocelot.Middleware;
using Ocelot.DependencyInjection;
using RG3.PF.RateLimit;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using RG3.BO.Auth.Provider;
using RG3.PF.Abstractions.Providers;
using RG3.PF.Caching.Redis.Extensions;
using Microsoft.AspNetCore.Http.Features;
using RG3.BO.Auth.Providers;
using RG3.BO.Abstractions.Provider;
using RG3.BO.Core.Attributes;
using RG3.BO.Core.Provider;
using RG3.PF.Caching.Memcached;
using RG3.DO.MySql;
using RG3.DO.Sqlite;
using RG3.DO.Oracle;
using RG3.DO.Sinoregal;
using RG3.DO.PostgreSQL;
using RG3.DO.Mapper.Json.Services;
using System;
using System.Net;
using Microsoft.AspNetCore.SpaServices.Extensions;
using RG3.BO.Core.Extenstions;
using RG3.BO.BI.Bridge.Services;
using RG3.BO.Abstractions.Interfaces;
using RG3.BO.Op.Provider;
//using RG3.WS.SignalR.Hubs;
using RG3.BO.DB.Providers;
using Microsoft.Extensions.FileProviders;
using RG3.BO.Core.Hubs;
using System.Net.WebSockets;
using RG3.PF.Caching.MongoDB.Extensions;
using RG3.PF.MessageQueue;
using RG3.PF.MessageQueue.Extensions;
//using LogDashboard;
//using Microsoft.AspNetCore.NodeServices;
namespace RG3.PF.Web.Host
{
public class Startup
{
/// <summary>
///
/// </summary>
public readonly IConfiguration _configuration;
///// <summary>
/////
///// </summary>
//public readonly BridgeService _bridgeService;
///// <summary>
/////
///// </summary>
//public readonly SqlConfigService _sqlConfigServe;
public Startup(IConfiguration configuration)
{
_configuration = configuration;
//, BridgeService bridgeService, SqlConfigService sqlConfigServe
//_bridgeService = bridgeService;
//_sqlConfigServe = sqlConfigServe;
}
/// <summary>
///
/// </summary>
/// <param name="services"></param>
[Obsolete]
public void ConfigureServices(IServiceCollection services)
{
////日志仪表盘
//services.AddLogDashboard();
////添加文件操作对象
//services.AddSingleton<IFileProvider, PhysicalFileProvider>();
#region 设置文件夹路径替换的基本信息
MapperPath _mp = new MapperPath();
_configuration.GetSection("mapperPath").Bind(_mp);
PhyPathUtil._mapperPath = _mp;
#endregion
//启动网关服务 gateway.provider
if (_configuration.GetValue<bool>("StartRoutes"))
{
services.AddOcelot(_configuration);
}
if (_configuration.GetValue<bool>("StartIpLimiting"))
{
//load general configuration from appsettings.json
services.Configure<IpRateLimitOptions>(_configuration.GetSection("IpRateLimiting"));
//load ip rules from appsettings.json
services.Configure<IpRateLimitPolicies>(_configuration.GetSection("IpRateLimitPolicies"));
// inject counter and rules stores
services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();
// configuration (resolvers, counter key builders)
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
}
//启用 Kestrel
if (_configuration.GetValue<bool>("Kestrel:Enabled"))
{
services.Configure<KestrelServerOptions>(_configuration.GetSection("Kestrel"));
}
//启用跨域
services.AddCors();
//services.AddNodeServices((action) => { });
services.AddNodeServices(options =>
{
// options.LaunchWithDebugging = false;
// options.ProjectPath = "/Users/loogn/scripts";
});
//设置表单提交的最大长度
//services.Configure<FormOptions>(options =>
//{
// options.KeyLengthLimit = 20480000;
//});
//添加http请求等参数信息获取
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//本地化和全球化
//添加
// 添加 Http客户端处理
services.AddHttpClient();
List<HttpClientConfig> hcc = new List<HttpClientConfig>();
_configuration.GetSection("httpClientHandler").Bind(hcc);
foreach (var item in hcc)
{
services.AddHttpClient(item.Key.ToString()).ConfigurePrimaryHttpMessageHandler(() =>
{
var temp = new HttpClientHandler()
{
MaxRequestContentBufferSize = item.Value.MaxRequestContentBufferSize == 0 ? 102400 : item.Value.MaxRequestContentBufferSize,
Proxy = item.Value.Proxy,
UseProxy = item.Value.UseProxy
};
temp.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true;
return temp;
});
//services.AddHttpClient(item.Key.ToString(), option =>
//{
// option.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
// option.Timeout = new TimeSpan(0, 0, 10);
//}).ConfigurePrimaryHttpMessageHandler(() =>
//{
// return new HttpClientHandler()
// {
// MaxRequestContentBufferSize = 102400,
// AutomaticDecompression = DecompressionMethods.GZip,
// ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true
// };
//});
}
services.AddSingleton<DesService, DesService>();
//sql调试使用 结合 operation:analysisDebug 和 operation:sqlDebug
// "sqlDebug": true, //数据库sql调试, operation
//"analysisDebug": true //性能调试
services.AddSingleton<IDebugProvider, DebugProvider>();
//添加本地注入服务
services.AddLocalService(); ;
services.AddDatabaseFeature();
services.AddSqlServerBatcherProvider();
services.AddMySqlBatcherProvider();
services.AddSqliteBatcherProvider();
services.AddOracleBatcherProvider();
services.AddPostgreSQLBatcherProvider();
services.AddSinoregalBatcherProvider();
services.AddSingleton<IConfigurationBuilderProvider, ConfigurationBuilderProvider>();
services.AddSingleton<IDbContext, DbContext>();
services.AddXmlMapperProvider();
//services.AddSingleton<IMapperProvider, XmlMapperProvider>();
//services.AddSingleton<IMapperProvider, JsonMapperProvider>();
//注入操作日志记录
services.AddSingleton<IOperateLog, BO.DB.Providers.OperateLogProvider>();
//文件操作
services.AddSingleton<IGuid, GuidRepository>();
services.AddSingleton<IFileAndImage, FileAndImageProvider>();
//使用Scoped方式为了调用 内置的其它服务
//services.AddScoped<ILoginProvider, LoginProvider>();
//services.AddScoped<ISingleLoginProvider, SingleLoginProvider>();
services.AddSingleton<ILoginProvider, LoginProvider>();
services.AddSingleton<ISingleLoginProvider, SingleLoginProvider>();
services.AddSingleton<ISaveExtendProvider, SaveExtendProvider>();
//RG3.BO.Qu mapper里面接口参数预处理,用于需要用到第三方接口数据作为参数 扩展
//使用时候 实现 IParamsPresetProvider 接口,并替换 ParamsPresetProvider
services.AddSingleton<IParamsPresetProvider, ParamsPresetProvider>();
//创建 token等信息
services.AddSingleton<IAuthProvider, AuthProvider>();
//权限信息
services.AddSingleton<IPopedomProvider, PopedomProvider>();
//services.AddSingleton<IConfigurationBuilderProvider, IConfigurationBuilderProvider>();
services.AddSingleton<IQuDataResultCache, QuDataResultProvider>();
services.AddSingleton<IDataBizCache, DataBizCacheProvider>();
//mapper 用户行为 未实现
services.AddSingleton<IUserBehaviorProvider, UserBehaviorProvider>();
//用户日志
services.AddSingleton<IUserLogProvider, UserLogProvider>();
//用户token 使用 IAuthProvider
//services.AddSingleton<IUserTokenProvider, UserTokenProvider>();
//订阅实现
services.AddSingleton<ISubPush, SubPushProvider>();
//基础数据 文件变更订阅和存储 未实现
services.AddSingleton<ISubPushBasis, SubPushBasisProvider>();
//维数据 文件变更订阅和存储 未实现
services.AddSingleton<ISubPushDimData, SubPushDimDataProvider>();
//bridge文件变更订阅和存储 未实现
services.AddSingleton<ISubPushBridge, SubPushBridgeProvider>();
//mapper 文件变更订阅和存储 未实现
services.AddSingleton<ISubPushMapper, SubPushMapperProvider>();
//消息推送 和订阅
//services.AddSingleton<ISubscribePublish, SubscribePublishProvider>();
services.AddRedisMQ(_configuration, null, 8);
//添加自定义缓存
services.AddMemoryCustomizeCache(_configuration);
if (_configuration.GetValue<string>("cache:dataType") == "redis")
{
//请求结果缓存信息
services.AddRedisCustomizeCache(_configuration, typeof(IDataResultCache), 4);
}
else if (_configuration.GetValue<string>("cache:dataType") == "mongodb")
{
//请求结果缓存信息
services.AddMongoDBCustomizeCache(_configuration, typeof(IDataResultCache));
}
if (_configuration.GetValue<string>("cache:loginType") == "redis")
{
//登录缓存信息
services.AddRedisCustomizeCache(_configuration, typeof(IDataLoginCache), 5);
}
else if (_configuration.GetValue<string>("cache:loginType") == "mongodb")
{
//登录缓存信息
services.AddMongoDBCustomizeCache(_configuration, typeof(IDataLoginCache));
}
if (_configuration.GetValue<string>("cache:mapperType") == "redis")
{
//config缓存信息 (app,mapper,bridge)
services.AddRedisCustomizeCache(_configuration, typeof(IDataMapperCache), 3);
}
else if (_configuration.GetValue<string>("cache:mapperType") == "mongodb")
{
//config缓存信息 (app,mapper,bridge)
services.AddMongoDBCustomizeCache(_configuration, typeof(IDataMapperCache));
}
//services.AddSingleton<IDataLoginCache, MemoryCacheProvider>();
//启用跨域
// services.AddCors();
//动态加载控制器dll 以及定义 json 输出格式
services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss";
//忽略空数据
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
//忽略默认值
options.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Include;
//设置枚举类型转换
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
//循环引用
// options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
#region token jwt 认证 以及 权限控制 cbg / cbg 20181127
////1、添加用户 接口访问拦截
////2、局部接口授权可以通过文件进行管理:config/app/base/app_route_authorized.json
services.AddSingleton<IVerifyApiProvider, VerifyApiProvider>();
services.AddMvcCore(options =>
{
//接口 XverifyApi 合法性验证
if (_configuration.GetValue<bool>("operation:verifyApi"))
{
options.Filters.Add<VerifyApiFilter>();
}
//用户登录拦截
if (_configuration.GetValue<bool>("operation:userFilter"))
{
options.Filters.Add<UserFilter>();
}
//用户行为记录
if (_configuration.GetValue<bool>("operation:userBehavior"))
{
options.Filters.Add<UserBehaviorFilter>();
}
});
#endregion
#region 添加websoket 等消息服务
//注入SignalR实时通讯,默认用json传输
services.AddSignalR(options =>
{
////客户端发保持连接请求到服务端最长间隔,默认30秒,改成4分钟,网页需跟着设置connection.keepAliveIntervalInMilliseconds = 12e4;即2分钟
//options.ClientTimeoutInterval = TimeSpan.FromMinutes(4);
////服务端发保持连接请求到客户端间隔,默认15秒,改成2分钟,网页需跟着设置connection.serverTimeoutInMilliseconds = 24e4;即4分钟
//options.KeepAliveInterval = TimeSpan.FromMinutes(2);
});
//services.AddCors(op =>
//{
// op.AddPolicy("*", set =>
// {
// set.SetIsOriginAllowed(origin => true)
// .AllowAnyHeader()
// .AllowAnyMethod()
// .AllowCredentials();
// });
//});
#endregion
}
/// <summary>
///
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//启动网关服务 gateway.provider
if (_configuration.GetValue<bool>("StartRoutes"))
{
app.UseOcelot();//.Wait();
}
//启动ip限流
if (_configuration.GetValue<bool>("StartIpLimiting"))
{
app.UseIpRateLimiting();
}
//services.AddHsts(options =>
//{
// options.Preload = true;
// options.IncludeSubDomains = true;
// options.MaxAge = TimeSpan.FromDays(60);
// options.ExcludedHosts.Add("example.com");
//});
//services.AddHttpsRedirection(options =>
//{
// options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
// options.HttpsPort = 5001;
//});
//添加RG3框架提供的中间件 UseAdminSafeListMiddleware UseAuthentication UseParameterVerify UseGlobalException
app.AddPFBasis(null, _configuration);
//if (_configuration.GetValue<bool>("operation:verifyApi"))
//{
// app.UseMiddleware<VerifyApiMiddleware>();
//}
//响应结果中间件 未实现
//app.UseHttpContextMiddleware();
app.UseRouting();
//启动wwwroot 文件服务
app.UseFileServer();
//允许跨域
string origins = _configuration.GetValue<string>("withOrigins");
List<string> originsValue = new List<string>();
_configuration.GetSection("withOriginsValue").Bind(originsValue);
app.UseCors(temp =>
{
if (originsValue != null && originsValue.Count > 0)
{
//webSocket 时候使用
temp.WithOrigins(originsValue.ToArray()).SetIsOriginAllowed(origin => true).AllowAnyMethod().AllowAnyHeader().AllowCredentials();
}
else if (origins == "*")
{
// .AllowCredentials().SetIsOriginAllowed(origin => true).AllowCredentials()
temp.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
}
else
{
//限制运行特定域名跨域访问
temp.WithOrigins(origins.Split(',')).AllowAnyMethod().AllowAnyHeader();
}
});
//var webSocketOptions = new WebSocketOptions()
//{
// KeepAliveInterval = TimeSpan.FromSeconds(120),
//};
//webSocketOptions.AllowedOrigins.Add("http://localhost:5775");
//webSocketOptions.AllowedOrigins.Add("http://www.localhost:5775");
//webSocketOptions.AllowedOrigins.Add("http://localhost:58582");
//webSocketOptions.AllowedOrigins.Add("http://www.localhost:58582");
//app.UseWebSockets(webSocketOptions);
//app.Use(async (context, next) =>
//{
// if (context.Request.Path == "/ws")
// {
// if (context.WebSockets.IsWebSocketRequest)
// {
// using (WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync())
// {
// await Echo(context, webSocket);
// }
// }
// else
// {
// context.Response.StatusCode = 400;
// }
// }
// else
// {
// await next();
// }
//});
////if (env.IsDevelopment())
////{
//app.UseDeveloperExceptionPage();
////}
//app.UseLogDashboard();
////app.Run(async (context) =>
////{
//// await context.Response.WriteAsync("Hello World!");
////});
app.UseEndpoints(endpoints =>
{
//endpoints.MapHub<ChatHub>("/ws/api/v3/chat");
//模块数据变更通知
if (_configuration.GetValue<bool>("websoket:open"))
{
endpoints.MapHub<MkeyHub>("/ws/api/v3/mkey");
}
endpoints.MapControllers();
});
}
}
}
#region https://docs.microsoft.com/zh-cn/aspnet/core/signalr/redis-backplane?view=aspnetcore-5.0
//services.AddSignalR()
// .AddMessagePackProtocol()
// .AddStackExchangeRedis(o =>
// {
// o.ConnectionFactory = async writer =>
// {
// var config = new ConfigurationOptions
// {
// AbortOnConnectFail = false
// };
// config.EndPoints.Add(IPAddress.Loopback, 0);
// config.SetDefaultPorts();
// var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
// connection.ConnectionFailed += (_, e) =>
// {
// Console.WriteLine("Connection to Redis failed.");
// };
// if (!connection.IsConnected)
// {
// Console.WriteLine("Did not connect to Redis.");
// }
// return connection;
// };
// });
#endregion
文档更新时间: 2021-08-07 12:09 作者:admin