-
Notifications
You must be signed in to change notification settings - Fork 4
/
Startup.UI.cs
287 lines (214 loc) · 11.5 KB
/
Startup.UI.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
using System;
using System.Reflection;
using Karambolo.Common;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.ResponseCaching;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using Microsoft.Net.Http.Headers;
using WebApp.Api.Infrastructure.Localization;
using WebApp.Core.Helpers;
using WebApp.Service.Settings;
using WebApp.UI.Infrastructure;
using WebApp.UI.Infrastructure.DataAnnotations;
using WebApp.UI.Infrastructure.ErrorHandling;
using WebApp.UI.Infrastructure.Filters;
using WebApp.UI.Infrastructure.Hosting;
using WebApp.UI.Infrastructure.Security;
using WebApp.UI.Infrastructure.Theming;
using WebApp.UI.Infrastructure.ViewFeatures;
using WebApp.UI.Models;
namespace WebApp.UI
{
public partial class Startup
{
internal const string UITenantId = "UI";
private sealed partial class UITenant : Tenant
{
private readonly Api.Startup _apiStartup;
public UITenant(string id, Startup startup, Assembly? entryAssembly = null)
: base(id, startup.Configuration, startup.Environment, entryAssembly)
{
_apiStartup = startup.ApiStartup;
IsRunningBehindProxy = _apiStartup.IsRunningBehindProxy;
UIOptions = startup.UIOptions!;
}
public bool IsRunningBehindProxy { get; }
public UIOptions UIOptions { get; }
public override Func<HttpContext, bool>? BranchPredicate => null;
protected override bool ShouldResolveFromRoot(ServiceDescriptor service) =>
// AddDataAnnotationsLocalization, AddViewLocalization calls AddLocalization under the hood, that is, it adds base localization services,
// but those are already registered in the root container and we need those shared instances
// https://github.com/dotnet/aspnetcore/blob/v3.1.18/src/Mvc/Mvc.Localization/src/MvcLocalizationServices.cs#L14
service.ServiceType == typeof(IStringLocalizerFactory) || service.ServiceType == typeof(IStringLocalizer<>);
partial void ConfigureMvcPartial(IMvcBuilder builder);
public override void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IAccountManager, AccountManager>();
services
.AddSingleton<IThemeProvider, ThemeProvider>()
.AddSingleton<IThemeManager, ThemeManager>();
#region Response compression
if (UIOptions.EnableResponseCompression)
{
services.AddResponseCompression();
services.Configure<ResponseCompressionOptions>(Configuration.GetSection("Response:Compression"));
}
#endregion
#region Bundling
if (Program.UsesDesignTimeBundling)
services.AddBundling();
else
Bundles.ConfigureServices(services, Configuration, Environment, UIOptions.Bundles);
#endregion
#region Security
// https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
.Bind(Configuration.GetSection($"{UISecurityOptions.DefaultSectionName}:Authentication"))
.Configure<IAccountManager>((options, accountManager) => options.Events = new UICookieAuthenticationEvents(accountManager));
services.AddAuthorization(options => AnonymousOnlyAttribute.AddPolicy(options));
services
.ReplaceLast(ServiceDescriptor.Singleton<IAuthorizationPolicyProvider, CustomAuthorizationPolicyProvider>())
.AddSingleton<IPageAuthorizationHelper, PageAuthorizationHelper>();
#endregion
#region View caching
if (UIOptions.Views.EnableResponseCaching)
{
services.AddResponseCaching();
services.Configure<ResponseCachingOptions>(Configuration.GetSection("Response:ViewCaching"));
}
#endregion
#region MVC
var mvcBuilder = services.AddRazorPages(options => options.Conventions.Add(new GlobalPageApplicationModelConvention()));
_apiStartup.ConfigureModelBinding(mvcBuilder);
_apiStartup.ConfigureModelValidation(mvcBuilder);
services.Configure<MvcViewOptions>(options => options.ClientModelValidatorProviders.Add(new DataAnnotationsClientLocalizationAdjuster()));
mvcBuilder
.ConfigureApplicationPartManager(manager =>
{
// ApplicationPartManager finds the Api assembly (as it is referenced), so we have to exclude it manually
// because we don't want the API controllers to be visible to the UI branch
// https://github.com/dotnet/aspnetcore/blob/v3.1.18/src/Mvc/Mvc.Core/src/DependencyInjection/MvcCoreServiceCollectionExtensions.cs#L81
manager.ApplicationParts.RemoveAll((part, _) => part is AssemblyPart assemblyPart && assemblyPart.Assembly == typeof(Api.Startup).Assembly);
});
services.ReplaceLast(ServiceDescriptor.Singleton<IHtmlGenerator, CustomHtmlGenerator>());
mvcBuilder
.AddViewLocalization();
services
.ReplaceLast(ServiceDescriptor.Singleton<IHtmlLocalizerFactory, ExtendedHtmlLocalizerFactory>())
.ReplaceLast(ServiceDescriptor.Transient<IViewLocalizer, ExtendedViewLocalizer>());
services.AddSingleton(typeof(RuntimeCompilationAwareValueCache<>));
if (UIOptions.EnableRazorRuntimeCompilation)
mvcBuilder.AddRazorRuntimeCompilation();
#endregion
#region Global Razor helpers
services.AddSingleton<IGlobalRazorHelpersFactory, GlobalRazorHelpersFactory>();
services.AddTransient(typeof(IGlobalRazorHelpers<>), typeof(GlobalRazorHelpers<>));
#endregion
ConfigureMvcPartial(mvcBuilder);
}
public override void Configure(IApplicationBuilder app)
{
var settingsProvider = app.ApplicationServices.GetRequiredService<ISettingsProvider>();
#region Exception handling
if (Environment.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();
}
if (UIOptions.EnableStatusCodePages)
app.UseStatusCodePages();
app.UseMiddleware<ExceptionFilterMiddleware>();
#endregion
if (!IsRunningBehindProxy)
app.UseHttpsRedirection();
#region Response compression
if (UIOptions.EnableResponseCompression)
app.UseResponseCompression();
#endregion
#region Bundling
if (Program.UsesDesignTimeBundling)
app.InitializeBundling();
else
app.UseBundling(new Bundles());
#endregion
#region Static files
var staticFileOptions = new StaticFileOptions();
if (UIOptions.StaticFiles.EnableResponseCaching)
staticFileOptions.OnPrepareResponse = context =>
{
var headers = context.Context.Response.GetTypedHeaders();
headers.CacheControl = new CacheControlHeaderValue { MaxAge = UIOptions.StaticFiles.CacheHeaderMaxAge ?? UIOptions.DefaultCacheHeaderMaxAge };
};
app.UseStaticFiles(staticFileOptions);
#endregion
#region Localization
if (settingsProvider.EnableLocalization())
{
var supportedCultures = settingsProvider.AvailableCultures(out var defaultCulture);
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(defaultCulture, defaultCulture),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures,
});
}
#endregion
app.UseRouting();
#region Security
app.UseAuthentication();
app.UseAuthorization();
#endregion
#region View caching
if (UIOptions.Views.EnableResponseCaching)
app.UseResponseCaching();
#endregion
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
// we need a custom IPageApplicationModelConvention implementation because PageConventionCollection doesn't provide
// a simpler way of global customization (e.g. adding filters to all pages of all areas) currently:
// https://github.com/dotnet/aspnetcore/issues/9783
private sealed class GlobalPageApplicationModelConvention : IPageApplicationModelConvention
{
public void Apply(PageApplicationModel model)
{
model.Filters.Add(new EnsureHandlerPageFilter());
Type pageDescriptorProviderType;
if ((pageDescriptorProviderType = model.HandlerType).HasInterface(typeof(IPageDescriptorProvider)) ||
(pageDescriptorProviderType = model.PageType).HasInterface(typeof(IPageDescriptorProvider)))
{
var pageDescriptor = PageDescriptor.Get(pageDescriptorProviderType);
if (pageDescriptor.GetAuthorizationPolicyAsync != null)
{
var policyName = CustomAuthorizationPolicyProvider.AuthorizePagePolicyPrefix + pageDescriptorProviderType.AssemblyQualifiedNameWithoutAssemblyDetails();
model.EndpointMetadata.Add(new AuthorizeAttribute(policyName));
}
}
}
}
}
}
}