forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStartup.cs
More file actions
204 lines (175 loc) · 7.86 KB
/
Startup.cs
File metadata and controls
204 lines (175 loc) · 7.86 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
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.IServices;
using Blog.Core.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
namespace Blog.Core
{
/// <summary>
/// 启动文件
/// </summary>
public class Startup
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="configuration"></param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// Configuration 属性
/// </summary>
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
/// <summary>
/// ConfigureServices 方法
/// </summary>
/// <param name="services"></param>
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//将 TService 中指定的类型的范围服务添加到实现
services.AddScoped<ICaching, MemoryCaching>();//记得把缓存注入!!!
services.AddScoped<IRedisCacheManager, RedisCacheManager>();
#region Automapper
services.AddAutoMapper(typeof(Startup));
#endregion
#region 配置信息
//Blog.Core.Repository.BaseDBConfig.ConnectionString = Configuration.GetSection("AppSettings:SqlServerConnection").Value;
#endregion
#region CORS
services.AddCors(c =>
{
//↓↓↓↓↓↓↓注意正式环境不要使用这种全开放的处理↓↓↓↓↓↓↓↓↓↓
c.AddPolicy("AllRequests", policy =>
{
policy
.AllowAnyOrigin()//允许任何源
.AllowAnyMethod()//允许任何方式
.AllowAnyHeader()//允许任何头
.AllowCredentials();//允许cookie
});
//↑↑↑↑↑↑↑注意正式环境不要使用这种全开放的处理↑↑↑↑↑↑↑↑↑↑
//一般采用这种方法
c.AddPolicy("LimitRequests", policy =>
{
policy
.WithOrigins("http://localhost:8020", "http://blog.core.xxx.com", "")//支持多个域名端口
.WithMethods("GET", "POST", "PUT", "DELETE")//请求方法添加到策略
.WithHeaders("authorization");//标头添加到策略
});
});
#endregion
#region Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v0.1.0",
Title = "Blog.Core API",
Description = "框架说明文档",
TermsOfService = "None",
Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "Blog.Core", Email = "Blog.Core@xxx.com", Url = "https://www.jianshu.com/u/94102b59cc2a" }
});
//就是这里
#region 读取xml信息
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "Blog.Core.xml");//这个就是刚刚配置的xml文件名
var xmlModelPath = Path.Combine(basePath, "Blog.Core.Model.xml");//这个就是Model层的xml文件名
c.IncludeXmlComments(xmlPath, true);//默认的第二个参数是false,这个是controller的注释,记得修改
c.IncludeXmlComments(xmlModelPath);
#endregion
#region Token绑定到ConfigureServices
//添加header验证信息
//c.OperationFilter<SwaggerHeader>();
var security = new Dictionary<string, IEnumerable<string>> { { "Blog.Core", new string[] { } }, };
c.AddSecurityRequirement(security);
//方案名称“Blog.Core”可自定义,上下一致即可
c.AddSecurityDefinition("Blog.Core", new ApiKeyScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入{token}\"",
Name = "Authorization",//jwt默认的参数名称
In = "header",//jwt默认存放Authorization信息的位置(请求头中)
Type = "apiKey"
});
#endregion
});
#endregion
#region Token服务注册
services.AddSingleton<IMemoryCache>(factory =>
{
var cache = new MemoryCache(new MemoryCacheOptions());
return cache;
});
services.AddAuthorization(options =>
{
options.AddPolicy("Admin", policy => policy.RequireClaim("AdminType").Build());//注册权限管理,可以自定义多个
});
#endregion
#region AutoFac
//实例化 AutoFac 容器
var builder = new ContainerBuilder();
//注册要通过反射创建的组件
//builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
builder.RegisterType<BlogCacheAOP>();//可以直接替换其他拦截器
var assemblysServices = Assembly.Load("Blog.Core.Services");
//builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces();//指定已扫描程序集中的类型注册为提供所有其实现的接口。
builder.RegisterAssemblyTypes(assemblysServices)
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
.InterceptedBy(typeof(BlogCacheAOP));//允许将拦截器服务的列表分配给注册。可以直接替换其他拦截器
var assemblysRepository = Assembly.Load("Blog.Core.Repository");
builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();
//将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.
/// <summary>
/// 方法
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
#region Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
});
#endregion
app.UseMiddleware<TokenAuth>();
app.UseMvc();
}
}
}