-
Notifications
You must be signed in to change notification settings - Fork 0
/
IApplicationBuilderExtensions.cs
179 lines (149 loc) · 6.63 KB
/
IApplicationBuilderExtensions.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
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.CookiePolicy;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
namespace SystemLibrary.Common.Web.Extensions;
/// <summary>
/// Extension methods for ApplicationBuilder object
/// </summary>
public static partial class IApplicationBuilderExtensions
{
public static IApplicationBuilder UseBranch(this IApplicationBuilder app, IWebHostEnvironment env, string branch, AppBuilderOptions options = null)
{
if (branch == null) throw new System.Exception("A branch cannot be null, either pass a branch like /api, or use the method UseCommonWebApp if you do not want a branch");
app.MapWhen(context => context?.Request != null && context.Request.Path.Value != null && context.Request.Path.StartsWithSegments(branch), branch =>
{
branch.UseCommonWebApp(env, options);
});
return app;
}
/// <summary>
/// Register common middlewares for a web application
///
/// Note: This is usually the first registration of middlewares you have, unless your own logging middleware/tracing goes before
///
/// This will register:
/// - Http to Https redirection middleware, client and server side
/// - Routing urls to controllers middleware
/// - /api/ urls to controllers middleware
/// - Authentication and Authorization attributes' middleware
/// - Servince static files such as .css, .js, .jpg, etc... middleware
/// - Forwarded headers middleware
/// - Razor pages and Mvc middleware
/// - Secure cookie policy middleware
/// - Secure cookie policy (http only middleware
/// - Recompiling razor pages (saving a cshtml file) middleware
/// - Exception page middleware
/// </summary>
/// <example>
/// Startup.cs/Program.cs:
/// <code>
/// public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
/// {
/// var options = new AppBuilderOptions();
///
/// app.CommonWebApplicationBuilder(options);
/// }
/// </code>
/// </example>
public static IApplicationBuilder UseCommonWebApp(this IApplicationBuilder app, IWebHostEnvironment env, AppBuilderOptions options = null)
{
if (options == null)
options = new AppBuilderOptions();
if (options.UseDeveloperPage)
app.UseDeveloperExceptionPage();
if (options.UseForwardedHeaders)
app.UseForwardedHeaders();
if (options.UseHsts)
app.UseHsts();
if (options.UseHttpsRedirection)
app.UseHttpsRedirection();
if (options.UseStaticFiles)
{
StaticFileOptions staticFileOptions = new StaticFileOptions
{
ServeUnknownFileTypes = options.StaticFilesServeUnknownFileTypes,
HttpsCompression = HttpsCompressionMode.Compress,
RedirectToAppendTrailingSlash = false,
OnPrepareResponse = ctx =>
{
if (ctx.Context.Response.Headers.ContainsKey("Cache-Control") != true)
ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age=" + options.StaticFilesMaxAgeSeconds);
},
};
var dir = env?.WebRootPath ?? Directory.GetCurrentDirectory();
if (env?.WebRootPath == null)
{
if (dir.Contains("\\bin\\") || dir.Contains("/bin/"))
dir = Directory.GetParent(dir).FullName;
if (dir.Contains("\\bin\\") || dir.Contains("/bin/"))
dir = Directory.GetParent(dir).FullName;
if (dir.Contains("\\bin\\") || dir.Contains("/bin/"))
dir = Directory.GetParent(dir).FullName;
}
staticFileOptions.FileProvider = new PhysicalFileProvider(dir);
staticFileOptions.RequestPath = new PathString(options.StaticFilesRequestPath ?? "");
app.UseStaticFiles(staticFileOptions);
}
if (options.UseRouting)
app.UseRouting();
if (options.UseCookiePolicy)
{
var cookieOptions = new CookiePolicyOptions() { };
cookieOptions.Secure = CookieSecurePolicy.SameAsRequest;
cookieOptions.HttpOnly = HttpOnlyPolicy.None;
cookieOptions.MinimumSameSitePolicy = SameSiteMode.Lax;
cookieOptions.CheckConsentNeeded = context => false;
app.UseCookiePolicy(cookieOptions);
}
if (options.UseOutputCache && !options.UseOutputCacheAfterAuthentication)
app.UseOutputCache();
if (!options.UseOutputCacheAfterAuthentication)
{
if (options.UseBrotliResponseCompression || options.UseGzipResponseCompression)
{
app.UseWhen((context) => Compress.IsEligibleForCompression(context, options), appCompression =>
{
appCompression.UseResponseCompression();
});
}
}
if (options.UseAuthentication)
app.UseAuthentication();
if (options.UseOutputCache && options.UseOutputCacheAfterAuthentication)
app.UseOutputCache();
if (options.UseOutputCacheAfterAuthentication)
{
if (options.UseBrotliResponseCompression || options.UseGzipResponseCompression)
{
app.UseWhen((context) => Compress.IsEligibleForCompression(context, options), appCompression =>
{
appCompression.UseResponseCompression();
});
}
}
if (options.UseAuthorization)
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
if (options.UseRazorPages)
endpoints.MapRazorPages();
if (options.UseControllers)
{
endpoints.MapControllers();
endpoints.MapDefaultControllerRoute();
}
if (options.UseApiControllers)
endpoints.MapControllerRoute("api/{controller}/{action}/{id?}", "api/{controller}/{action}/{id?}");
});
HttpContextInstance.HttpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
ActionContextInstance.ActionContextAccessor = app.ApplicationServices.GetRequiredService<IActionContextAccessor>();
Services.ServiceProviderInstance = app.ApplicationServices;
return app;
}
}