Startup.cs
10.3 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
using Autofac;
using HHECS.Application.Service;
using HHECS.Dal;
using HHECS.Infrastructure.QiYeWeiXin;
using HHECS.Web.Aop;
using HHECS.Web.Models;
using HHECS.Web.Resources.Shared;
using HHECS.WebCommon.AuthorizationPolicy;
using HHECS.WebCommon.Config;
using HHECS.WebCommon.SystemHelp.Json;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
namespace HHECS.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
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;
});
//中英文翻译1:添加本地化服务,设置资源文件路径
services.AddLocalization(options => options.ResourcesPath = "Resources");
//中英文翻译2: 设置支持的文化列表
var supportedCultures = new[] { "zh-cn", "en-us" };
var defaultCulture = supportedCultures[1];
services.Configure<RequestLocalizationOptions>(options =>
{
options.SetDefaultCulture(defaultCulture)
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
// 明确设置请求文化提供者顺序
options.RequestCultureProviders.Clear();
options.RequestCultureProviders.Add(new QueryStringRequestCultureProvider()); // 1. 查询字符串
options.RequestCultureProviders.Add(new CookieRequestCultureProvider()); // 2. Cookie
// 可选:添加自定义提供者,如果没有Cookie和查询参数,强制使用英文
options.RequestCultureProviders.Add(new CustomRequestCultureProvider(async context =>
{
// 如果没有设置任何语言偏好,默认使用英文
return new ProviderCultureResult(defaultCulture);
}));
});
services.AddMvc(option =>
{
option.ModelBinderProviders.Insert(0, new JsonBinderProvider());
//加入全局异常类
option.Filters.Add<HttpGlobalExceptionFilter>();
option.EnableEndpointRouting = false;
}).AddJsonOptions(option => option.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter()))
//中英文翻译3:
//这是为视图启用本地化
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
#region 定时器
services.AddTransient<MaintainRecordWork>();
//Quartz调度中心
services.AddQuartz(q =>
{
//用于注入
q.UseMicrosoftDependencyInjectionJobFactory();
// 基本Quartz调度器、作业和触发器配置
var jobKey = new JobKey("MaintainRecordWork", "regularWorkGroup");
q.AddJob<MaintainRecordWork>(jobKey, j => j.WithDescription("My regular work"));
q.AddTrigger(t => t
.WithIdentity("Trigger")
.ForJob(jobKey)
.StartNow()
.WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(40))//开始秒数 40s
.RepeatForever())//持续工作
.WithDescription("My regular work trigger"));
//var jobKey2 = new JobKey(nameof(MaintainRecordWorkV2));
//q.AddJob<MaintainRecordWorkV2>(jobKey2, x => x.WithIdentity(jobKey2));
//q.AddTrigger(t => t.WithIdentity($"{jobKey2}_Trigger").ForJob(jobKey2).StartNow().WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMinutes(1)).RepeatForever()));
});
// ASP.NET核心托管-添加Quartz服务
services.AddQuartzServer(options =>
{
// 关闭时,我们希望作业正常完成
options.WaitForJobsToComplete = false;
});
#endregion
//services.AddMvc().AddRazorRuntimeCompilation();
services.AddControllersWithViews();
services.AddRazorPages().AddRazorRuntimeCompilation();
//Asp.Net Core获取请求上下文HttpContext https://www.cnblogs.com/tianma3798/p/10361644.html
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(t =>
{
t.LoginPath = "/Login/Index";
t.LogoutPath = "/Login/Index";
t.AccessDeniedPath = "/Login/Index";
});
services.AddAuthorization(config =>
{
config.AddPolicy("operation", policy => policy.Requirements.Add(new OperationAuthorizeRequirement(new PermissionService())));
});
//读取配置文件节点(AppCustomSettings) 使用方法:AppSettings.GetAppSeting("xxx");
AppSettings.SetAppSetting(Configuration.GetSection("AppCustomSettings"));
//操作日志
services.AddScoped<OperLogFilter>();
//xss攻击防御
services.AddScoped<XSSFilterAttribute>();
services.AddHttpClient("WxClient", config =>
{
config.BaseAddress = new Uri(Configuration["Wx:baseurl"]);
config.DefaultRequestHeaders.Add("Accept", "application/json");
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
#region apk https://www.cnblogs.com/1175429393wljblog/p/8624679.html
// 1. 静态文件
app.UseStaticFiles(
new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
{
{ ".apk", "application/vnd.android.package-archive" }
})
});
#endregion
app.UseAuthentication();
// 2. 路由(必须先有路由,才能有认证)
app.UseRouting();
// 4. 认证
app.UseAuthentication();
// 5. 授权
app.UseAuthorization();
#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}/errors/500.html");
}
});
});
app.UseStatusCodePagesWithRedirects("/errors/{0}");
#endregion
////企业微信消息推送2
QiYiWeiXinGlobalContext.HttpClientFactory = app.ApplicationServices.GetService<IHttpClientFactory>();
QiYiWeiXinGlobalContext.Configuration = Configuration;
////企业微信消息推送1 调用
//var content = QiYiWeiXinGlobalContext.GetContent(QiYiWeiXinGlobalContext.GetAgentId(), "", "推送测试");
//QiYiWeiXinGlobalContext.SendMsg(content);
// 6. 本地化 中英文翻译4: 添加请求本地化中间件
var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(localizationOptions.Value);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "area",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapAreaControllerRoute(
name: "areas", "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
});
}
/// <summary>
/// 容器注册服务
/// </summary>
/// <param name="containerBuilder"></param>
public void ConfigureContainer(ContainerBuilder containerBuilder)
{
//指定服务的注册
var assmbly = Assembly.GetAssembly(typeof(DALHelper));
var assmbly2 = Assembly.GetAssembly(typeof(BaseService));
containerBuilder.RegisterAssemblyTypes(assmbly2).Where(t => t.Name.EndsWith("Service")).AsSelf().InstancePerDependency();
}
}
}