/
Startup.cs
308 lines (265 loc) · 11.6 KB
/
Startup.cs
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
using AutoMapper;
using FluentValidation;
using FluentValidation.AspNetCore;
using ImpromptuInterface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using Serilog;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using WebApiDemo.AuthorizationHandlers;
using WebApiDemo.Database;
using WebApiDemo.Extensions;
using WebApiDemo.HealthCheck;
using WebApiDemo.HttpClients;
using WebApiDemo.Middlewares;
using WebApiDemo.Models;
using WebApiDemo.Providers;
using WebApiDemo.Repositories;
using WebApiDemo.Services;
using WebApiDemo.Services.Tenants;
using WebApiDemo.Validators;
namespace WebApiDemo
{
public class Startup
{
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
{
// Init Serilog configuration
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
Configuration = configuration;
LoggerFactory = loggerFactory;
ServiceProvider = serviceProvider;
TypesToRegister = Assembly.Load("WebApiDemo")
.GetTypes()
.Where(x => !string.IsNullOrEmpty(x.Namespace))
.Where(x => x.IsClass)
.Where(x => x.Namespace.StartsWith("WebApiDemo.Services.Tenants")).ToList();
}
public IConfiguration Configuration { get; }
public ILoggerFactory LoggerFactory { get; }
public IServiceProvider ServiceProvider { get; }
public List<Type> TypesToRegister { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#region DemoAuthentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "https://login.microsoftonline.com/136544d9-038e-4646-afff-10accb370679";
options.Audience = "257b6c36-1168-4aac-be93-6f2cd81cec43";
options.TokenValidationParameters.ValidateLifetime = true;
options.TokenValidationParameters.ClockSkew = TimeSpan.Zero;
});
#endregion
#region DemoAuthorization
services.AddAuthorization(opts =>
{
opts.AddPolicy("SurveyCreator", p =>
{
// Using value text for demo show, else use enum : ClaimTypes.Role
p.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "SurveyCreator");
});
opts.AddPolicy("SuperSurveyCreator", p =>
{
// Using value text for demo show, else use enum : ClaimTypes.Role
//p.RequireClaim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "SurveyCreator");
//p.RequireClaim("groups", "8115e3be-ac7a-4886-a1e6-5b6aaf810a8f");
p.Requirements.Add(new SuperSurveyCreatorRequirement("SurveyCreator", "8115e3be-ac7a-4886-a1e6-5b6aaf810a8f"));
});
});
// Authorization handlers
services.AddSingleton<IAuthorizationHandler, SuperSurveyCreatorAutorizationHandler>();
#endregion
#region Demo Validator
services.AddSingleton<IValidator<User>, UserValidator>();
#endregion
#region DemoConfig
var config = new {
ConnectionString = ServiceProvider.GetService<IConfiguration>()["MySecretConnectionString"]
}
.ActLike<IConfig>(); // <-- from Azure Keyvault
services.AddScoped<IMyRepository>(c =>
{
return new MyRepository(config);
});
services.Configure<SmtpConfiguration>(Configuration.GetSection("SmtpConfiguration"));
#endregion
#region DemoCRUD EF + ORMLite
//services.AddScoped<ICountryRepository>(c =>
//{
// return new OrmLiteCountryRepository(config);
//});
services.AddDbContext<DemoDbContext>(options => options.UseSqlServer(config.ConnectionString));
services.AddScoped<ICountryRepository, EFCountryRepository>();
#endregion
#region DemoHealthCheck
services.AddHealthChecks()
.AddCheck("MyDatabase", new SqlConnectionHealthCheck(config.ConnectionString ?? string.Empty));
#endregion
#region DemoCache
services.AddMemoryCache();
#endregion
#region DemoResponseCaching
// caching response for middlewares
services.AddResponseCaching();
#endregion
#region DemoMapping Automapper
services.AddAutoMapper();
#endregion
#region MVC + FluentValidation
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddFluentValidation();
#endregion
#region override modelstate for fluentvalidation
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = (context) =>
{
var errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(p => p.ErrorMessage)).ToList();
var result = new
{
Code = "00009",
Message = "Validation errors",
Errors = errors
};
return new BadRequestObjectResult(result);
};
});
#endregion
#region DemoDocumenting
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API + profiler integrated on top left page", Version = "v1" });
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
});
#endregion
#region DemoProfiling
services.AddMiniProfiler(options =>
options.RouteBasePath = "/profiler"
);
#endregion
#region DemoHttpClient
services.AddHttpClient<IDataClient, DataClient>(client =>
{
client.BaseAddress = new Uri("http://localhost:56190/api/");
})
.AddPolicyHandlers("PolicyConfig", LoggerFactory, Configuration);
services.AddHttpClient<IStreamingClient, StreamingClient>(client =>
{
client.BaseAddress = new Uri("https://anthonygiretti.blob.core.windows.net/videos/");
});
#endregion
#region DemoCompression
services.AddResponseCompression(options =>
{
options.Providers.Add<GzipCompressionProvider>();
options.EnableForHttps = true;
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "application/x-sql", "video/mp4" });
});
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
#endregion
#region DemoApiVersionning
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
});
#endregion
#region DemoMultiTenant
// Classes to register
TypesToRegister.ForEach(x => services.AddScoped(x));
// Multitenant interface with its related classes
services.AddScopedDynamic<ITenantService>(TypesToRegister);
// Global Service provider
services.AddScoped(typeof(IServicesProvider<>), typeof(ServicesProvider<>));
#endregion
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// CACHING all response that return 200 ok
//app.UseResponseCaching();
#region MiniProfiler
// profiling, url to see last profile check: http://localhost:62258/profiler/results
app.UseMiniProfiler();
#endregion
#region Documenting
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "api-doc";
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
// index.html customizable downloadable here: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/index.html
// this custom html has miniprofiler integration
c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("WebApiDemo.SwaggerIndex.html");
});
#endregion
#region Logging
loggerFactory.AddSerilog();
#endregion
#region Authenticating
app.UseAuthentication();
#endregion
#region Global caching middleware
app.UseMiddleware<CachingMiddleware>();
#endregion
#region Global exception handling middleware
app.UseMiddleware<CustomExceptionMiddleware>();
#endregion
#region HealthCheck
app.UseHealthChecks("/health", new HealthCheckOptions()
{
ResultStatusCodes =
{
[HealthStatus.Healthy] = StatusCodes.Status200OK,
[HealthStatus.Degraded] = StatusCodes.Status200OK,
[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable
}
});
#endregion
#region Compression
//app.UseResponseCompression();
#endregion
// mini profiler
//app.UseMiddleware<MiniProfilerMiddleware>();
app.UseMvc();
}
}
}