This repository has been archived by the owner on Dec 18, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 527
/
Startup.cs
187 lines (160 loc) · 7.48 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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Https.Internal;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace SampleApp
{
public class Startup
{
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger("Default");
// Add an exception handler that prevents throwing due to large request body size
app.Use(async (context, next) =>
{
// Limit the request body to 1kb
context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 1024;
try
{
await next.Invoke();
}
catch (BadHttpRequestException ex) when (ex.StatusCode == StatusCodes.Status413RequestEntityTooLarge) { }
});
app.Run(async context =>
{
// Drain the request body
await context.Request.Body.CopyToAsync(Stream.Null);
var connectionFeature = context.Connection;
logger.LogDebug($"Peer: {connectionFeature.RemoteIpAddress?.ToString()}:{connectionFeature.RemotePort}"
+ $"{Environment.NewLine}"
+ $"Sock: {connectionFeature.LocalIpAddress?.ToString()}:{connectionFeature.LocalPort}");
var response = $"hello, world{Environment.NewLine}";
context.Response.ContentLength = response.Length;
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(response);
});
}
public static Task Main(string[] args)
{
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
Console.WriteLine("Unobserved exception: {0}", e.Exception);
};
var hostBuilder = new WebHostBuilder()
.ConfigureLogging((_, factory) =>
{
factory.SetMinimumLevel(LogLevel.Debug);
factory.AddConsole();
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
})
.UseKestrel((context, options) =>
{
if (context.HostingEnvironment.IsDevelopment())
{
ShowConfig(context.Configuration);
}
var basePort = context.Configuration.GetValue<int?>("BASE_PORT") ?? 5000;
options.ConfigureEndpointDefaults(opt =>
{
opt.NoDelay = true;
});
options.ConfigureHttpsDefaults(httpsOptions =>
{
httpsOptions.SslProtocols = SslProtocols.Tls12;
});
// Run callbacks on the transport thread
options.ApplicationSchedulingMode = SchedulingMode.Inline;
options.Listen(IPAddress.Loopback, basePort, listenOptions =>
{
// Uncomment the following to enable Nagle's algorithm for this endpoint.
//listenOptions.NoDelay = false;
listenOptions.UseConnectionLogging();
});
options.Listen(IPAddress.Loopback, basePort + 1, listenOptions =>
{
listenOptions.UseHttps();
listenOptions.UseConnectionLogging();
});
options.ListenLocalhost(basePort + 2, listenOptions =>
{
// Use default dev cert
listenOptions.UseHttps();
});
options.ListenAnyIP(basePort + 3);
options.ListenAnyIP(basePort + 4, listenOptions =>
{
listenOptions.UseHttps(StoreName.My, "localhost", allowInvalid: true);
});
options.ListenAnyIP(basePort + 5, listenOptions =>
{
listenOptions.UseHttps(httpsOptions =>
{
var localhostCert = CertificateLoader.LoadFromStoreCert("localhost", "My", StoreLocation.CurrentUser, allowInvalid: true);
httpsOptions.ServerCertificateSelector = (features, name) =>
{
// Here you would check the name, select an appropriate cert, and provide a fallback or fail for null names.
return localhostCert;
};
});
});
options
.Configure()
.Endpoint(IPAddress.Loopback, basePort + 6)
.LocalhostEndpoint(basePort + 7)
.Load();
options
.Configure(context.Configuration.GetSection("Kestrel"))
.Endpoint("NamedEndpoint", opt =>
{
opt.ListenOptions.NoDelay = true;
})
.Endpoint("NamedHttpsEndpoint", opt =>
{
opt.HttpsOptions.SslProtocols = SslProtocols.Tls12;
});
options.UseSystemd();
// The following section should be used to demo sockets
//options.ListenUnixSocket("/tmp/kestrel-test.sock");
})
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>();
if (string.Equals(Process.GetCurrentProcess().Id.ToString(), Environment.GetEnvironmentVariable("LISTEN_PID")))
{
// Use libuv if activated by systemd, since that's currently the only transport that supports being passed a socket handle.
hostBuilder.UseLibuv(options =>
{
// Uncomment the following line to change the default number of libuv threads for all endpoints.
// options.ThreadCount = 4;
});
}
return hostBuilder.Build().RunAsync();
}
private static void ShowConfig(IConfiguration config)
{
foreach (var pair in config.GetChildren())
{
Console.WriteLine($"{pair.Path} - {pair.Value}");
ShowConfig(pair);
}
}
}
}