pan
8 天以前 ad88253aab4f38bb98d5516fecd1264c1e0235df
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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 Quartz;
using Serilog;
using System.Net.Security;
using System.Reflection;
using System.Runtime.ConstrainedExecution;
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.Filter;
using WIDESEA_WMSServer.Jobs;
 
var builder = WebApplication.CreateBuilder(args);
 
//// ÅäÖÃSerilog£¨Ê¾ÀýÅäÖã¬Ò²¿Éͨ¹ýappsettings.jsonÅäÖã©
//Log.Logger = new LoggerConfiguration()
//  .MinimumLevel.Information()
//  .WriteTo.Console()
//  .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day)
//  .CreateLogger();
 
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information() // ÉèÖÃÈ«¾Ö×îµÍÈÕÖ¾¼¶±ðΪ Information
                                // ÖØÐ´Ìض¨ÃüÃû¿Õ¼äµÄÈÕÖ¾¼¶±ð£¬¹ýÂËϵͳÔëÒô
    .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning) // Microsoft Ïà¹ØÈÕÖ¾Ö»ÏÔʾ Warning ¼°ÒÔÉÏ
    .MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning) // Ìرð¹ýÂË AspNetCore µÄÈÕÖ¾
    .MinimumLevel.Override("Microsoft.Hosting.Lifetime", Serilog.Events.LogEventLevel.Information) // µ«±£ÁôÆô¶¯/¹Ø±ÕÐÅÏ¢
    .Enrich.FromLogContext() // ·á¸»ÈÕÖ¾ÉÏÏÂÎÄ£¬¶ÔÓÚºóÐøÀ©Õ¹ºÜÓÐÓÃ
    .WriteTo.Console( // ÅäÖÃÊä³öµ½¿ØÖÆÌ¨
        outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}" // ¶¨Òå¼ò½àµÄÊä³öÄ£°å
    )
    .WriteTo.File( // ÅäÖÃÊä³öµ½Îļþ
        path: "logs/log-.txt", // ÈÕÖ¾Îļþ·¾¶£¬»á×Ô¶¯´´½¨ logs Îļþ¼Ð
        rollingInterval: RollingInterval.Day, // °´Ìì¹ö¶¯ÈÕÖ¾Îļþ
        retainedFileCountLimit: 7, // ×î¶à±£Áô7ÌìµÄÈÕÖ¾
        outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
    )
    .CreateLogger();
 
 
builder.Host.UseSerilog(); // Ê¹ÓÃSerilog×÷ΪÈÕÖ¾Ìṩ³ÌÐò
 
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.ConfigureApplication();
 
//App.ExpDateTime = DateTime.Parse("2025-03-31 00:00:00");//¹ýÆÚʱ¼ä
 
// 2¡¢ÅäÖ÷þÎñ
builder.Services.AddSingleton(new AppSettings(builder.Configuration));//×¢²á
builder.Services.AddAllOptionRegister();//¶ÁÈ¡ÅäÖÃÎļþ
builder.Services.AddMemoryCacheSetup();//»º´æ
builder.Services.AddWebSocketSetup();
builder.Services.AddSqlsugarSetup();//SqlSugar Æô¶¯·þÎñ
builder.Services.AddDbSetup();//Db Æô¶¯·þÎñ
builder.Services.AddInitializationHostServiceSetup();//Ó¦Óóõʼ»¯·þÎñ×¢Èë
//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.AddAuthorizationSetup();
 
builder.Services.AddIpPolicyRateLimitSetup(builder.Configuration);//IPLimitÏÞÁ÷ Æô¶¯·þÎñ
 
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);
 
builder.Services.AddHttpClient("ESSUrl", (serviceProvider, client) =>
{
    var essurl = AppSettings.GetValue("ESSUrl").ObjToString();
    client.BaseAddress = new Uri(essurl!);
    client.Timeout = TimeSpan.FromSeconds(30);
 
});
 
builder.Services.AddHttpClient("MESUrl", (serviceProvider, client) =>
{
    var mesurl = AppSettings.GetValue("MESUrl").ObjToString();
    client.BaseAddress = new Uri(mesurl!);
    client.Timeout = TimeSpan.FromSeconds(30);
 
});
 
builder.Services.AddHttpClient("ERPUrl", (serviceProvider, client) =>
{
    var erpurl = AppSettings.GetValue("ERPUrl").ObjToString();
    client.BaseAddress = new Uri(erpurl!);
    client.Timeout = TimeSpan.FromSeconds(30);
 
})  ;
 
builder.Services.AddQuartz(q =>
{
    
    var jobKey = new JobKey("ErpJob");
    q.AddJob<ErpJob>(opts => opts.WithIdentity(jobKey));
 
 
    // Ìí¼Ó´¥·¢Æ÷ - Ã¿Ìì10:00, 14:00, 20:00Ö´ÐÐ
    q.AddTrigger(opts => opts
        .ForJob(jobKey)
        .WithIdentity("ErpJob-trigger")
        .WithCronSchedule("0 0 10,14,20 * * ?"));
 
    var inventoryLockJobKey = new JobKey("InventoryLockJob");
    q.AddJob<InventoryLockJob>(opts => opts.WithIdentity(inventoryLockJobKey));
 
    q.AddTrigger(opts => opts
        .ForJob(inventoryLockJobKey)
        .WithIdentity("InventoryLockJob-trigger")
        .WithCronSchedule("0 0/10 * * * ?")); // Ã¿10·ÖÖÓÖ´ÐÐÒ»´Î
 
});
 
 
builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
var app = builder.Build();
 
 
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();
 
app.UseCors(AppSettings.Get(new string[] { "Cors", "PolicyName" }));
 
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.UseAuthentication();
app.UseAuthorization();
 
app.MapControllers();
 
app.Run();