Skip to content

Commit 95cd9e7

Browse files
committed
use https redirect jincod#6
1 parent f858567 commit 95cd9e7

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

src/AspNetCoreDemoApp/Startup.cs

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
using Microsoft.AspNetCore.Builder;
3-
using Microsoft.AspNetCore.Hosting;
4-
using Microsoft.AspNetCore.Rewrite;
3+
using Microsoft.AspNetCore.HttpOverrides;
54
using Microsoft.Extensions.DependencyInjection;
65

76
namespace AspNetCoreDemoApp
@@ -11,6 +10,7 @@ public class Startup
1110
public void ConfigureServices(IServiceCollection services)
1211
{
1312
services
13+
.AddHttpsRedirection(options => { options.HttpsPort = 443; })
1414
.AddMvcCore()
1515
.AddCors(options =>
1616
{
@@ -19,10 +19,26 @@ public void ConfigureServices(IServiceCollection services)
1919
.AllowAnyMethod()
2020
.AllowAnyHeader());
2121
});
22+
23+
services.Configure<ForwardedHeadersOptions>(options =>
24+
{
25+
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |
26+
ForwardedHeaders.XForwardedProto;
27+
options.KnownNetworks.Clear();
28+
options.KnownProxies.Clear();
29+
});
2230
}
2331

24-
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
32+
public void Configure(IApplicationBuilder app)
2533
{
34+
app.UseForwardedHeaders();
35+
36+
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HEROKU_APP_NAME")))
37+
{
38+
Console.WriteLine("Use https redirection");
39+
app.UseHttpsRedirection();
40+
}
41+
2642
app
2743
.UseRouting()
2844
.UseDefaultFiles()
@@ -32,13 +48,6 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
3248
{
3349
endpoints.MapDefaultControllerRoute();
3450
});
35-
36-
if (env.EnvironmentName == "Production")
37-
{
38-
var options = new RewriteOptions()
39-
.AddRedirectToHttpsPermanent();
40-
app.UseRewriter(options);
41-
}
4251
}
4352
}
4453
}

0 commit comments

Comments
 (0)