wanshenmean
6 天以前 5171d3f59b89389bf75293afd210cfa6de4ccff7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Serilog;
using Serilog.Formatting.Json;
using System.Reflection;
using System.Text;
using WIDESEA_Core;
using WIDESEA_Core.Authorization;
using WIDESEA_Core.BaseServices;
using WIDESEA_Core.Core;
using WIDESEA_Core.Extensions;
using WIDESEA_Core.Filter;
using WIDESEA_Core.Helper;
//using WIDESEA_Core.HostedService;
using WIDESEA_Core.Middlewares;
using WIDESEA_WMSServer.BackgroundServices;
using WIDESEA_WMSServer.Filter;
 
var builder = WebApplication.CreateBuilder(args);
 
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureContainer<ContainerBuilder>(builder =>
{
    builder.RegisterModule<AutofacModuleRegister>(); // 注册接口依赖注入
    builder.RegisterModule<AutofacPropertityModuleReg>(); // 注册属性注入
}).ConfigureAppConfiguration((hostingContext, config) =>
{
    hostingContext.Configuration.ConfigureApplication();
    config.Sources.Clear();
    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
});
 
builder.Host.UseSerilog((context, services, loggerConfiguration) =>
{
    loggerConfiguration
        .ReadFrom.Configuration(context.Configuration)
        .ReadFrom.Services(services)
        //.Enrich.FromLogContext()
        .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
        .WriteTo.File(
            //new JsonFormatter(renderMessage: true),
            "logs/serilog-.log",
            outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
            rollingInterval: RollingInterval.Day,
            retainedFileCountLimit: 30,
            // 每个日志文件最大大小(字节),此处设置为10MB
            fileSizeLimitBytes: 10 * 1024 * 1024,
            shared: true
            )
         // 6. 可选:输出到Seq日志服务器(结构化日志服务器)
         // 需要安装 Serilog.Sinks.Seq NuGet包,并确保Seq服务在 http://localhost:5341 运行
         // 如不需要Seq日志,注释掉下方代码即可
         .WriteTo.Seq(
             serverUrl: "http://localhost:5341",
             apiKey: "CWVa8UWQ9CdUp9GWXCPL", // 如Seq需要ApiKey则配置真实密钥
             batchPostingLimit: 1000, // 批量发送数量
             period: TimeSpan.FromSeconds(2) // 发送间隔
         );
});
builder.ConfigureApplication();
 
// App.ExpDateTime = DateTime.Parse("2025-03-31 00:00:00"); // 设置过期时间
 
// 2. 配置服务
builder.Services.AddSingleton(new AppSettings(builder.Configuration)); // 注册配置
builder.Services.AddAllOptionRegister(); // 获取配置文件
builder.Services.AddSingleton<RoundRobinService>();
builder.Services.Configure<AutoOutboundTaskOptions>(
    builder.Configuration.GetSection("AutoOutboundTask"));
builder.Services.AddMemoryCacheSetup(); // 缓存服务
builder.Services.AddWebSocketSetup();
builder.Services.AddSqlsugarSetup(); // SqlSugar 数据库配置
builder.Services.AddDbSetup(); // Db 数据库配置
builder.Services.AddInitializationHostServiceSetup(); // 应用程序初始化服务注册
builder.Services.AddHostedService<AutoOutboundTaskBackgroundService>();  // 启动自动出库任务后台服务
builder.Services.AddHostedService<StockMonitorBackgroundService>();  // 启动库存监控后台服务
// builder.Services.AddHostedService<PermissionDataHostService>(); // 权限数据服务
builder.Services.AddAutoMapperSetup();
 
builder.Services.AddCorsSetup();
 
builder.Services.AddMiniProfilerSetup();
 
builder.Services.AddSwaggerSetup();
 
builder.Services.AddHttpContextSetup();
 
 
builder.Services.AddMvc(options =>
{
    options.Filters.Add(typeof(ApiAuthorizeFilter));
    options.Filters.Add(typeof(ActionExecuteFilter));
});
 
builder.Services.AddSignalR();
 
builder.Services.AddScoped<HttpClientHelper>();
 
builder.Services.AddAuthorizationSetup();
 
builder.Services.AddIpPolicyRateLimitSetup(builder.Configuration); // IP限流 中间件注册
 
builder.Services.AddScoped<UseServiceDIAttribute>();
 
builder.Services.AddSession();
 
builder.Services.AddHttpClient();
 
builder.Services.AddControllers(o =>
{
    o.Filters.Add(typeof(GlobalExceptionsFilter)); // 全局异常处理
})
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
    //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
    options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
    options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
 
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
 
 
var app = builder.Build();
 
// 3. 配置中间件
app.UseMiniProfiler(); // 性能分析
app.ConfigureApplication(); // 应用配置
app.UseApplicationSetup(); // 应用启动
 
app.UseAllServicesMiddle(builder.Services);
 
app.UseSession();
app.UseSwaggerAuthorized();
app.UseSwaggerMiddle(() => Assembly.GetExecutingAssembly().GetManifestResourceStream("WIDESEA_WMSServer.index.html") ?? throw new Exception("WIDESEA_WMSServer.index.html文件不存在"));
app.UseIpLimitMiddle();
app.UseApiLogMiddleware();
// todo
// app.UseRecordAccessLogsMiddle();
 
 
DefaultFilesOptions defaultFilesOptions = new DefaultFilesOptions();
defaultFilesOptions.DefaultFileNames.Clear();
defaultFilesOptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defaultFilesOptions);
app.UseMiddleware<HttpRequestMiddleware>();
app.UseStaticFiles();
 
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(App.WebHostEnvironment.WebRootPath)
});
 
app.UseCookiePolicy();
app.UseStatusCodePages();
 
app.UseRouting();
 
app.UseCors(AppSettings.Get(new string[] { "Cors", "PolicyName" }));
 
app.UseAuthentication();
app.UseAuthorization();
 
app.MapControllers();
 
app.MapHub<WIDESEA_WMSServer.Hubs.StockHub>("/stockHub");
 
app.Run();