-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathWebApplication.cs
More file actions
299 lines (257 loc) · 11.4 KB
/
Copy pathWebApplication.cs
File metadata and controls
299 lines (257 loc) · 11.4 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// The web application used to configure the http pipeline, and routes.
/// </summary>
public class WebApplication : IHost, IDisposable, IApplicationBuilder, IEndpointRouteBuilder
{
internal const string EndpointRouteBuilder = "__EndpointRouteBuilder";
private readonly IHost _host;
private readonly List<EndpointDataSource> _dataSources = new List<EndpointDataSource>();
internal WebApplication(IHost host)
{
_host = host;
ApplicationBuilder = new ApplicationBuilder(host.Services);
Logger = host.Services.GetRequiredService<ILoggerFactory>().CreateLogger(Environment.ApplicationName);
}
/// <summary>
/// The application's configured services.
/// </summary>
public IServiceProvider Services => _host.Services;
/// <summary>
/// The application's configured <see cref="IConfiguration"/>.
/// </summary>
public IConfiguration Configuration => _host.Services.GetRequiredService<IConfiguration>();
/// <summary>
/// The application's configured <see cref="IWebHostEnvironment"/>.
/// </summary>
public IWebHostEnvironment Environment => _host.Services.GetRequiredService<IWebHostEnvironment>();
/// <summary>
/// Allows consumers to be notified of application lifetime events.
/// </summary>
public IHostApplicationLifetime ApplicationLifetime => _host.Services.GetRequiredService<IHostApplicationLifetime>();
/// <summary>
/// The logger factory for the application.
/// </summary>
public ILoggerFactory LoggerFactory => _host.Services.GetRequiredService<ILoggerFactory>();
/// <summary>
/// The default logger for the application.
/// </summary>
public ILogger Logger { get; }
/// <summary>
/// The list of addresses that the HTTP server is bound to.
/// </summary>
public IEnumerable<string> Addresses => ServerFeatures.Get<IServerAddressesFeature>().Addresses;
/// <summary>
/// A collection of HTTP features of the server.
/// </summary>
public IFeatureCollection ServerFeatures => _host.Services.GetRequiredService<IServer>().Features;
IServiceProvider IApplicationBuilder.ApplicationServices { get => ApplicationBuilder.ApplicationServices; set => ApplicationBuilder.ApplicationServices = value; }
internal IDictionary<string, object> Properties => ApplicationBuilder.Properties;
IDictionary<string, object> IApplicationBuilder.Properties => Properties;
internal ICollection<EndpointDataSource> DataSources => _dataSources;
ICollection<EndpointDataSource> IEndpointRouteBuilder.DataSources => DataSources;
internal IEndpointRouteBuilder RouteBuilder
{
get
{
Properties.TryGetValue(EndpointRouteBuilder, out var value);
return (IEndpointRouteBuilder)value;
}
}
internal ApplicationBuilder ApplicationBuilder { get; }
IServiceProvider IEndpointRouteBuilder.ServiceProvider => Services;
/// <summary>
/// Sets the URLs the web server will listen on.
/// </summary>
/// <param name="urls">A set of urls.</param>
public void Listen(params string[] urls)
{
var addresses = ServerFeatures.Get<IServerAddressesFeature>().Addresses;
if (addresses.IsReadOnly)
{
throw new NotSupportedException("Changing the URL isn't supported.");
}
addresses.Clear();
foreach (var u in urls)
{
addresses.Add(u);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="WebApplicationBuilder"/> class with pre-configured defaults.
/// </summary>
/// <returns>The <see cref="WebApplicationBuilder"/></returns>
public static WebApplicationBuilder CreateBuilder()
{
// The assumption here is that this API is called by the application directly
// this might give a better approximation of the default application name
return new WebApplicationBuilder(
Assembly.GetCallingAssembly(),
builder => ConfigureBuilder(builder, args: null));
}
/// <summary>
/// Initializes a new instance of the <see cref="WebApplicationBuilder"/> class with pre-configured defaults.
/// </summary>
/// <param name="args">Command line arguments</param>
/// <returns>The <see cref="WebApplicationBuilder"/></returns>
public static WebApplicationBuilder CreateBuilder(string[] args)
{
return new WebApplicationBuilder(
Assembly.GetCallingAssembly(),
builder => ConfigureBuilder(builder, args));
}
/// <summary>
/// Initializes a new instance of the <see cref="WebApplication"/> class with pre-configured defaults.
/// </summary>
/// <param name="args">Command line arguments</param>
/// <returns>The <see cref="WebApplication"/></returns>
public static WebApplication Create(string[] args)
{
return new WebApplicationBuilder(
Assembly.GetCallingAssembly(),
builder => ConfigureBuilder(builder, args)).Build();
}
/// <summary>
/// Initializes a new instance of the <see cref="WebApplication"/> class with pre-configured defaults.
/// </summary>
/// <returns>The <see cref="WebApplication"/></returns>
public static WebApplication Create()
{
return new WebApplicationBuilder(
Assembly.GetCallingAssembly(),
builder => ConfigureBuilder(builder, args: null)).Build();
}
/// <summary>
/// Start the application.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task StartAsync(CancellationToken cancellationToken = default)
{
return _host.StartAsync(cancellationToken);
}
/// <summary>
/// Shuts down the application.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public Task StopAsync(CancellationToken cancellationToken = default)
{
return _host.StopAsync(cancellationToken);
}
/// <summary>
/// Disposes the application.
/// </summary>
public void Dispose()
{
_host.Dispose();
}
internal RequestDelegate Build() => ApplicationBuilder.Build();
RequestDelegate IApplicationBuilder.Build() => Build();
IApplicationBuilder IApplicationBuilder.New()
{
// REVIEW: Should this be wrapping another type?
return ApplicationBuilder.New();
}
IApplicationBuilder IApplicationBuilder.Use(Func<RequestDelegate, RequestDelegate> middleware)
{
ApplicationBuilder.Use(middleware);
return this;
}
IApplicationBuilder IEndpointRouteBuilder.CreateApplicationBuilder() => ApplicationBuilder.New();
/// <summary>
/// Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered.
/// </summary>
/// <param name="cancellationToken">The token to trigger shutdown.</param>
/// <returns>A <see cref="Task"/>that represents the asynchronous operation.</returns>
public Task RunAsync(CancellationToken cancellationToken = default)
{
return HostingAbstractionsHostExtensions.RunAsync(this, cancellationToken);
}
/// <summary>
/// Runs an application and block the calling thread until host shutdown.
/// </summary>
public void Run()
{
HostingAbstractionsHostExtensions.Run(this);
}
private static void ConfigureBuilder(IHostBuilder builder, string[] args)
{
// Keep in sync with this Host.CreateDefaultBuilder https://github.com/dotnet/extensions/blob/cb60ad143f61f0d96b0860895065351e86f79a10/src/Hosting/Hosting/src/Host.cs#L56
builder.UseContentRoot(Directory.GetCurrentDirectory());
builder.ConfigureHostConfiguration(config =>
{
config.AddEnvironmentVariables(prefix: "DOTNET_");
if (args != null)
{
config.AddCommandLine(args);
}
});
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
var isWindows = OperatingSystem.IsWindows();
// IMPORTANT: This needs to be added *before* configuration is loaded, this lets
// the defaults be overridden by the configuration.
if (isWindows)
{
// Default the EventLogLoggerProvider to warning or above
logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning);
}
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
if (isWindows)
{
// Add the EventLogLoggerProvider on windows machines
logging.AddEventLog();
}
})
.UseDefaultServiceProvider((context, options) =>
{
var isDevelopment = context.HostingEnvironment.IsDevelopment();
options.ValidateScopes = isDevelopment;
options.ValidateOnBuild = isDevelopment;
});
}
}
}