forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStartup.cs
More file actions
483 lines (391 loc) · 21.1 KB
/
Startup.cs
File metadata and controls
483 lines (391 loc) · 21.1 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using AutoMapper;
using Blog.Core.AOP;
using Blog.Core.AuthHelper;
using Blog.Core.Common;
using Blog.Core.Filter;
using Blog.Core.Log;
using Blog.Core.Model;
using log4net;
using log4net.Config;
using log4net.Repository;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Serialization;
using StackExchange.Profiling.Storage;
using Swashbuckle.AspNetCore.Swagger;
using static Blog.Core.SwaggerHelper.CustomApiVersion;
namespace Blog.Core
{
public class Startup
{
/// <summary>
/// log4net 仓储库
/// </summary>
public static ILoggerRepository repository { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//log4net
repository = LogManager.CreateRepository("Blog.Core");
//指定配置文件,如果这里你遇到问题,应该是使用了InProcess模式,请查看Blog.Core.csproj,并删之
XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
}
public IConfiguration Configuration { get; }
private const string ApiName = "Blog.Core";
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
#region 部分服务注入-netcore自带方法
//缓存注入
services.AddScoped<ICaching, MemoryCaching>();
services.AddSingleton<IMemoryCache>(factory =>
{
var cache = new MemoryCache(new MemoryCacheOptions());
return cache;
});
//Redis注入
services.AddSingleton<IRedisCacheManager, RedisCacheManager>();
//log日志注入
services.AddSingleton<ILoggerHelper, LogHelper>();
#endregion
#region 初始化DB
services.AddScoped<Blog.Core.Model.Models.DBSeed>();
services.AddScoped<Blog.Core.Model.Models.MyContext>();
#endregion
#region Automapper
services.AddAutoMapper(typeof(Startup));
#endregion
#region CORS
//跨域第二种方法,声明策略,记得下边app中配置
services.AddCors(c =>
{
//↓↓↓↓↓↓↓注意正式环境不要使用这种全开放的处理↓↓↓↓↓↓↓↓↓↓
c.AddPolicy("AllRequests", policy =>
{
policy
.AllowAnyOrigin()//允许任何源
.AllowAnyMethod()//允许任何方式
.AllowAnyHeader()//允许任何头
.AllowCredentials();//允许cookie
});
//↑↑↑↑↑↑↑注意正式环境不要使用这种全开放的处理↑↑↑↑↑↑↑↑↑↑
//一般采用这种方法
c.AddPolicy("LimitRequests", policy =>
{
policy
.WithOrigins("http://127.0.0.1:1818", "http://localhost:8080", "http://localhost:8021", "http://localhost:8081", "http://localhost:1818")//支持多个域名端口,注意端口号后不要带/斜杆:比如localhost:8000/,是错的
.AllowAnyHeader()//Ensures that the policy allows any header.
.AllowAnyMethod();
});
});
//跨域第一种办法,注意下边 Configure 中进行配置
//services.AddCors();
#endregion
#region MiniProfiler
services.AddMiniProfiler(options =>
{
options.RouteBasePath = "/profiler";
(options.Storage as MemoryCacheStorage).CacheDuration = TimeSpan.FromMinutes(10);
}
);
#endregion
#region Swagger UI Service
var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
services.AddSwaggerGen(c =>
{
//遍历出全部的版本,做文档信息展示
typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
{
c.SwaggerDoc(version, new Info
{
// {ApiName} 定义成全局变量,方便修改
Version = version,
Title = $"{ApiName} 接口文档",
Description = $"{ApiName} HTTP API " + version,
TermsOfService = "None",
Contact = new Contact { Name = "Blog.Core", Email = "Blog.Core@xxx.com", Url = "https://www.jianshu.com/u/94102b59cc2a" }
});
// 按相对路径排序,作者:Alby
c.OrderActionsBy(o => o.RelativePath);
});
//就是这里
var xmlPath = Path.Combine(basePath, "Blog.Core.xml");//这个就是刚刚配置的xml文件名
c.IncludeXmlComments(xmlPath, true);//默认的第二个参数是false,这个是controller的注释,记得修改
var xmlModelPath = Path.Combine(basePath, "Blog.Core.Model.xml");//这个就是Model层的xml文件名
c.IncludeXmlComments(xmlModelPath);
#region Token绑定到ConfigureServices
//添加header验证信息
//c.OperationFilter<SwaggerHeader>();
// 发行人
var IssuerName = (Configuration.GetSection("Audience"))["Issuer"];
var security = new Dictionary<string, IEnumerable<string>> { { IssuerName, new string[] { } }, };
c.AddSecurityRequirement(security);
//方案名称“Blog.Core”可自定义,上下一致即可
c.AddSecurityDefinition(IssuerName, new ApiKeyScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
Name = "Authorization",//jwt默认的参数名称
In = "header",//jwt默认存放Authorization信息的位置(请求头中)
Type = "apiKey"
});
#endregion
});
#endregion
#region MVC + GlobalExceptions
//注入全局异常捕获
services.AddMvc(o =>
{
// 全局异常过滤
o.Filters.Add(typeof(GlobalExceptionsFilter));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
// 取消默认驼峰
.AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); });
#endregion
#region Authorize权限设置三种情况
//使用说明:
//如果你只是简单的基于角色授权的,第一步:【1/2 简单角色授权】,第二步:配置【统一认证】,第三步:开启中间件app.UseMiddleware<JwtTokenAuth>()不能验证过期,或者 app.UseAuthentication();可以验证过期时间
//如果你是用的复杂的策略授权,配置权限在数据库,第一步:【3复杂策略授权】,第二步:配置【统一认证】,第三步:开启中间件app.UseAuthentication();
//综上所述,设置权限,必须要三步走,涉及授权策略 + 配置认证 + 开启授权中间件,只不过自定义的中间件不能验证过期时间,所以我都是用官方的。
#region 【1/2、简单角色授权】
#region 1、基于角色的API授权
// 1【授权】、这个很简单,其他什么都不用做,
// 无需配置服务,只需要在API层的controller上边,增加特性即可,注意,只能是角色的:
// [Authorize(Roles = "Admin")]
// 2【认证】、然后在下边的configure里,配置中间件即可:app.UseMiddleware<JwtTokenAuth>();但是这个方法,无法验证过期时间,所以如果需要验证过期时间,还是需要下边的第三种方法,官方认证
#endregion
#region 2、基于策略的授权(简单版)
// 1【授权】、这个和上边的异曲同工,好处就是不用在controller中,写多个 roles 。
// 然后这么写 [Authorize(Policy = "Admin")]
services.AddAuthorization(options =>
{
options.AddPolicy("Client", policy => policy.RequireRole("Client").Build());
options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
options.AddPolicy("SystemOrAdmin", policy => policy.RequireRole("Admin", "System"));
});
// 2【认证】、然后在下边的configure里,配置中间件即可:app.UseMiddleware<JwtTokenAuth>();但是这个方法,无法验证过期时间,所以如果需要验证过期时间,还是需要下边的第三种方法,官方认证
#endregion
#endregion
#region 【3、复杂策略授权】
#region 参数
//读取配置文件
var audienceConfig = Configuration.GetSection("Audience");
var symmetricKeyAsBase64 = audienceConfig["Secret"];
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray);
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
// 如果要数据库动态绑定,这里先留个空,后边处理器里动态赋值
var permission = new List<PermissionItem>();
// 角色与接口的权限要求参数
var permissionRequirement = new PermissionRequirement(
"/api/denied",// 拒绝授权的跳转地址(目前无用)
permission,
ClaimTypes.Role,//基于角色的授权
audienceConfig["Issuer"],//发行人
audienceConfig["Audience"],//听众
signingCredentials,//签名凭据
expiration: TimeSpan.FromSeconds(60*5)//接口的过期时间
);
#endregion
//【授权】
services.AddAuthorization(options =>
{
options.AddPolicy("Permission",
policy => policy.Requirements.Add(permissionRequirement));
});
#endregion
#region 【统一认证】
// 令牌验证参数
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = audienceConfig["Issuer"],//发行人
ValidateAudience = true,
ValidAudience = audienceConfig["Audience"],//订阅人
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};
//2.1【认证】、core自带官方JWT认证
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.TokenValidationParameters = tokenValidationParameters;
o.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
// 如果过期,则把<是否过期>添加到,返回头信息中
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
//2.2【认证】、IdentityServer4 认证 (暂时忽略)
//services.AddAuthentication("Bearer")
// .AddIdentityServerAuthentication(options =>
// {
// options.Authority = "http://localhost:5002";
// options.RequireHttpsMetadata = false;
// options.ApiName = "blog.core.api";
// });
// 注入权限处理器
services.AddSingleton<IAuthorizationHandler, PermissionHandler>();
services.AddSingleton(permissionRequirement);
#endregion
#endregion
#region AutoFac DI
//实例化 AutoFac 容器
var builder = new ContainerBuilder();
//注册要通过反射创建的组件
//builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
builder.RegisterType<BlogCacheAOP>();//可以直接替换其他拦截器
builder.RegisterType<BlogRedisCacheAOP>();//可以直接替换其他拦截器
builder.RegisterType<BlogLogAOP>();//这样可以注入第二个
// ※※★※※ 如果你是第一次下载项目,请先F6编译,然后再F5执行,※※★※※
#region 带有接口层的服务注入
#region Service.dll 注入,有对应接口
//获取项目绝对路径,请注意,这个是实现类的dll文件,不是接口 IService.dll ,注入容器当然是Activatore
try
{
var servicesDllFile = Path.Combine(basePath, "Blog.Core.Services.dll");
var assemblysServices = Assembly.LoadFile(servicesDllFile);//直接采用加载文件的方法 ※※★※※ 如果你是第一次下载项目,请先F6编译,然后再F5执行,※※★※※
//builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces();//指定已扫描程序集中的类型注册为提供所有其实现的接口。
// AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。
var cacheType = new List<Type>();
if (Appsettings.app(new string[] { "AppSettings", "RedisCaching", "Enabled" }).ObjToBool())
{
cacheType.Add(typeof(BlogRedisCacheAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "MemoryCachingAOP", "Enabled" }).ObjToBool())
{
cacheType.Add(typeof(BlogCacheAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "LogoAOP", "Enabled" }).ObjToBool())
{
cacheType.Add(typeof(BlogLogAOP));
}
builder.RegisterAssemblyTypes(assemblysServices)
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
// 如果你想注入两个,就这么写 InterceptedBy(typeof(BlogCacheAOP), typeof(BlogLogAOP));
// 如果想使用Redis缓存,请必须开启 redis 服务,端口号我的是6319,如果不一样还是无效,否则请使用memory缓存 BlogCacheAOP
.InterceptedBy(cacheType.ToArray());//允许将拦截器服务的列表分配给注册。
#endregion
#region Repository.dll 注入,有对应接口
var repositoryDllFile = Path.Combine(basePath, "Blog.Core.Repository.dll");
var assemblysRepository = Assembly.LoadFile(repositoryDllFile);
builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();
}
catch (Exception)
{
throw new Exception("※※★※※ 如果你是第一次下载项目,请先F6编译,然后再F5执行,因为解耦了 ※※★※※");
}
#endregion
#endregion
#region 没有接口层的服务层注入
////因为没有接口层,所以不能实现解耦,只能用 Load 方法。
////var assemblysServicesNoInterfaces = Assembly.Load("Blog.Core.Services");
////builder.RegisterAssemblyTypes(assemblysServicesNoInterfaces);
#endregion
#region 没有接口的单独类 class 注入
////只能注入该类中的虚方法
builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(Love)))
.EnableClassInterceptors()
.InterceptedBy(typeof(BlogLogAOP));
#endregion
//将services填充到Autofac容器生成器中
builder.Populate(services);
//使用已进行的组件登记创建新容器
var ApplicationContainer = builder.Build();
#endregion
return new AutofacServiceProvider(ApplicationContainer);//第三方IOC接管 core内置DI容器
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
#region Environment
if (env.IsDevelopment())
{
// 在开发环境中,使用异常页面,这样可以暴露错误堆栈信息,所以不要放在生产环境。
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// 在非开发环境中,使用HTTP严格安全传输(or HSTS) 对于保护web安全是非常重要的。
// 强制实施 HTTPS 在 ASP.NET Core,配合 app.UseHttpsRedirection
//app.UseHsts();
}
#endregion
#region MiniProfiler
app.UseMiniProfiler();
#endregion
#region Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
//根据版本名称倒序 遍历展示
typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
{
c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{ApiName} {version}");
});
c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Blog.Core.index.html");//这里是配合MiniProfiler进行性能监控的,《文章:完美基于AOP的接口性能分析》,如果你不需要,可以暂时先注释掉,不影响大局。
c.RoutePrefix = ""; //路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉
});
#endregion
#region Authen
//此授权认证方法已经放弃,请使用下边的官方验证方法。但是如果你还想传User的全局变量,还是可以继续使用中间件
//app.UseMiddleware<JwtTokenAuth>();
//如果你想使用官方认证,必须在上边ConfigureService 中,配置JWT的认证服务 (.AddAuthentication 和 .AddJwtBearer 二者缺一不可)
app.UseAuthentication();
#endregion
#region CORS
//跨域第二种方法,使用策略,详细策略信息在ConfigureService中
app.UseCors("LimitRequests");//将 CORS 中间件添加到 web 应用程序管线中, 以允许跨域请求。
#region 跨域第一种版本
//跨域第一种版本,请要ConfigureService中配置服务 services.AddCors();
// app.UseCors(options => options.WithOrigins("http://localhost:8021").AllowAnyHeader()
//.AllowAnyMethod());
#endregion
#endregion
// 跳转https
app.UseHttpsRedirection();
// 使用静态文件
app.UseStaticFiles();
// 使用cookie
app.UseCookiePolicy();
// 返回错误码
app.UseStatusCodePages();//把错误码返回前台,比如是404
app.UseMvc();
}
}
}