Startup.cs
12.7 KB
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
using Autofac.Extensions.DependencyInjection;
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Hh.Mes.Service;
using Hh.Mes.Service.Repository;
using Hh.Mes.Service.SystemAuth;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Quartz.AspNetCore;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using WebMvc.Aop;
namespace WebMvc
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
#region 自定义配置appsettings.json 节点 AppSettings.SetAppSetting(Configuration.GetSection("AppCustomSettings"));
AppSettings.SetAppSetting(Configuration.GetSection("AppCustomSettings"));
ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend1 = AppSettings.GetAppSeting("AppCustomExtend1");
ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend2 = AppSettings.GetAppSeting("AppCustomExtend2");
ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend3 = AppSettings.GetAppSeting("AppCustomExtend3");
ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend4 = AppSettings.GetAppSeting("AppCustomExtend4");
ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend5 = AppSettings.GetAppSeting("AppCustomExtend5");
ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend6 = AppSettings.GetAppSeting("AppCustomExtend6");
ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend7 = AppSettings.GetAppSeting("AppCustomExtend7");
ConfigRead.GetInstance.GetAppsetConnection().AppCustomExtend8 = AppSettings.GetAppSeting("AppCustomExtend8");
#endregion
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
options.ValueLengthLimit = int.MaxValue;
options.KeyLengthLimit = int.MaxValue;
options.MultipartBodyLengthLimit = int.MaxValue;
options.MultipartBoundaryLengthLimit = int.MaxValue;
//解决文件上传Request body too large
options.MultipartBodyLengthLimit = 268435456;
});
services.AddMvc(option =>
{
option.ModelBinderProviders.Insert(0, new JsonBinderProvider());
//加入全局异常类
option.Filters.Add<Aop.HttpGlobalExceptionFilter>();
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//Asp.Net Core获取请求上下文HttpContext https://www.cnblogs.com/tianma3798/p/10361644.html
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddMemoryCache();
services.AddOptions();
#region HTTPS
//services.AddMvc(options =>
//{
// options.SslPort = ConfigRead.GetInstance.GetAppsetConnection().WebPort;
// options.Filters.Add(new RequireHttpsAttribute());
//});
//services.AddAntiforgery(
// options =>
// {
// options.Cookie.Name = "_af";
// options.Cookie.HttpOnly = true;
// options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
// options.HeaderName = "X-XSRF-TOKEN";
// });
#endregion
//数据库连接地址
var connectionString = ConfigRead.GetInstance.GetAppsetConnection().BaseDBContext;
#region 启用Quartz中间件
services.AddQuartz(options =>
{
options.UseSqlServer(connectionString);
options.UseProperties(false);
});
#endregion
#region 添加Swagger中间件
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "华恒API",
Description = "华恒API接口",
});
//分组显示
options.SwaggerDoc("Andriod", new Info
{
Title = "安卓接口v1",
Version = "Andriod" ,
Description= "华恒Andriod接口"
});
//分组显示
options.SwaggerDoc("华恒大屏界面接口", new Info
{
Title = "华恒大屏界面接口",
Version = "ScreenInterfaceAPI",
Description = "华恒大屏界面接口"
});
//注入WebAPI注释文件给Swagger
var xmlPath = Path.Combine(AppContext.BaseDirectory, "WebMvc.xml");
options.IncludeXmlComments(xmlPath, true);
//var assembly = Assembly.GetAssembly(typeof(BaseDBContext));
//options.IncludeXmlComments(assembly.Location.Replace("dll", "xml"));
options.IgnoreObsoleteActions();
});
#endregion
services.AddSignalR();
//Redis 设置缓存
Task.Factory.StartNew(()=>
{
new BaseInfoCacheService().SetBaseInfoCacheFirst();
});
#region 注册SqlSugars、操作日志、XSS攻击防御等
//SqlSugars
services.BatchRegisterService(Program.service, Program.serviceSuffix);
services.AddDirectoryBrowser();
//操作日志
services.AddScoped<OperLogFilter>();
//services.AddScoped<InterfaceLogFilter>();
//xss攻击防御
services.AddScoped<XSSFilterAttribute>();
#endregion
#region 注入登录、授权等服务
services.AddScoped<LoginParse>();
services.AddScoped<AuthContextFactory>();
services.AddScoped<SystemAuthStrategy>();
services.AddScoped<NormalAuthStrategy>();
services.AddScoped(typeof(IAuth), typeof(LocalAuth));
#endregion
//使用AutoFac进行注入
return new AutofacServiceProvider(AutofacExt.InitAutofac(services));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
ConfigRead.GetInstance.GetAppsetConnection().IsDevelopment = false;
app.UseDeveloperExceptionPage();
}
else
{
if (IsExtSysFile()) return;
ConfigRead.GetInstance.GetAppsetConnection().IsDevelopment = true;
app.UseExceptionHandler("/htmlTemp");
}
app.UseStaticFiles();
Console.ResetColor();
#region apk https://www.cnblogs.com/1175429393wljblog/p/8624679.html
app.UseStaticFiles(
new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
{
{ ".apk", "application/vnd.android.package-archive" }
})
});
#endregion
#region 启用Swagger中间件
app.UseSwagger(
//c => c.RouteTemplate = "/swagger/{documentName}/swagger.json"
);
app.UseSwaggerUI(c =>
{
c.ShowExtensions();
c.SwaggerEndpoint("/swagger/v1/swagger.json", "华恒API接口文档");
c.SwaggerEndpoint("/swagger/Andriod/swagger.json", "华恒Andriod接口");
c.SwaggerEndpoint("/swagger/ScreenInterfaceAPI/swagger.json", "华恒大屏界面接口");
c.InjectStylesheet("/css/swagger.css");
c.DisplayOperationId();
c.DisplayRequestDuration();
c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.List);
});
#endregion
#region 启用Quartz中间件 开发环境不启用定时器,如果需要注释if条件
var isDevelopment = ConfigRead.GetInstance.GetAppsetConnection().IsDevelopment;
if (isDevelopment)
{
app.UseQuartz();
Console.WriteLine();
Console.WriteLine("友好提示:webApp线上环境已开启定作业任务,定时器code完成后需要在智能中控Job任务管理中配置!");
}
else {
//app.UseQuartz();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine();
Console.WriteLine("友好提示:基础版本扩展新项目后需要重新新建数据库和指定redisRedisDb!");
Console.WriteLine("友好提示:webApp线下环境未开启定作业任务,定时器code完成后需要在智能中控Job任务管理中配置!!");
Console.ResetColor();
}
Console.WriteLine();
#endregion
app.UseMvcWithDefaultRoute();
//app.UseSignalR(routes =>
//{
// routes.MapHub<ChartHub>("/ChartHub");
//});
#region http 500
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
if (context.Request.Headers["X-Requested-With"] != "XMLHttpRequest")
{
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync($@"{env.WebRootPath}/htmlTemp/500.html");
}
});
});
app.UseStatusCodePagesWithReExecute("/htmlTemp/{0}");
#endregion
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
}
private bool IsExtSysFile()
{
var webMvcPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "WebMvc.xml");
if (!File.Exists(webMvcPath))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebMvc.xml 文件路径不存在,请在bin/Debug 手动拷贝复制该文件到发布目录下面(和appsettings.json平级)!:" + webMvcPath);
Log4NetHelper.Instance.Info("WebMvc path:" + webMvcPath);
Console.ReadLine();
return true;
}
var wwwRootPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "wwwroot");
if (!Directory.Exists(wwwRootPath))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("wwwroot 文件夹不存在,请手动拷贝复制该文件到发布目录下面(和appsettings.json平级)!:" + webMvcPath);
Log4NetHelper.Instance.Info("wwwroot path:" + wwwRootPath);
Console.ReadLine();
return true;
}
var aaptPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "tools", "aapt.exe");
if (!File.Exists(aaptPath))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("aapt.exe 文件路径不存在,请在根目录tools/aapt.exe手动拷贝复制该文件到发布目录下面(和appsettings.json平级)!:" + aaptPath);
Log4NetHelper.Instance.Info("aaptPath path:" + aaptPath);
Console.ReadLine();
return true;
}
var unzipPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "tools", "unzip.exe");
if (!File.Exists(unzipPath))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("unzip.exe 文件路径不存在,请在根目录tools/unzip.exe手动拷贝复制该文件到发布目录下面(和appsettings.json平级)!:" + aaptPath);
Log4NetHelper.Instance.Info("unzip path:" + unzipPath);
Console.ReadLine();
return true;
}
return false;
}
}
}