Startup.cs
8.25 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
using Autofac;
using HHECS.Application.Service;
using HHECS.Dal;
using HHECS.Infrastructure.QiYeWeiXin;
using HHECS.Web.Aop;
using HHECS.Web.Models;
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.Mvc.Infrastructure;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
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;
});
services.AddMvc(option =>
{
option.ModelBinderProviders.Insert(0, new JsonBinderProvider());
//加入全局异常类
option.Filters.Add<HttpGlobalExceptionFilter>();
option.EnableEndpointRouting = false;
}).AddJsonOptions(option => option.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter()));
#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
app.UseStaticFiles(
new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
{
{ ".apk", "application/vnd.android.package-archive" }
})
});
#endregion
app.UseRouting();
#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);
app.UseAuthorization();
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();
}
}
}