2017-06-14 49 views
2

Enforcing SSL in a ASP.NET Core App指南MSDN,告訴我下面的代碼添加到我的Configure方法在Startup類,以重定向所有http請求httpsAddRedirectToHttps()不重定向到HTTPS

var options = new RewriteOptions() 
     .AddRedirectToHttps(); 

    app.UseRewriter(options); 

已經添加在正確的位置的代碼和測試在調試模式下的HTTP請求,我得到一個connection reset錯誤鉻:

This site can’t be reached 

The connection was reset. 
Try: 
Checking the connection 
Checking the proxy and the firewall 
Running Windows Network Diagnostics 
ERR_CONNECTION_RESET 

我試圖訪問相同的URL(包括端口。 。我認爲哪裏可能會出錯?)如果我使用https ... I.E,我會在地址欄中輸入http://localhost:44376而不是https://localhost:44376

Configuration方法的削減版本是這樣的:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
    loggerFactory.AddDebug(); 

    var options = new RewriteOptions() 
     .AddRedirectToHttps(); 

    app.UseRewriter(options); 

    if (env.IsDevelopment()) 
    { 
     app.UseDeveloperExceptionPage(); 
     app.UseDatabaseErrorPage(); 
     app.UseBrowserLink(); 
    } 
    else 
    { 
     app.UseExceptionHandler("/Home/Error"); 
    } 

    app.UseStaticFiles(); 

    app.UseIdentity(); 

    app.UseFacebookAuthentication(new FacebookOptions() 
    { 
     AppId = Configuration["Authentication_FacebookAppId"], 
     AppSecret = Configuration["Authentication_FacebookAppSecret"] 
    }); 

    app.UseMvc(routes => 
    { 
     routes.MapRoute(
      name: "default", 
      template: "{controller=Home}/{action=Index}/{id?}"); 
    }); 
} 

回答

0

由於這github post確認,我是在正確的線路認爲它很可能是造成這一問題的端口。 (從本質上講,你可以不聽的同一個端口上httphttps請求。)

對我來說,修復實際上是三個方面:

首先,你需要小心你如何運行你的應用程序中發展。在Windows上運行visual studio時,默認是使用IIS/IIS Express啓動。這會導致問題,因爲它使用項目設置中定義的應用程序url,而不是我們嘗試通過啓動類傳遞給kestrel的url。 (這是在launchSettings.jsoniisSettings部分定義的applicationUrl

如果你展開下拉上在Visual Studio中的start按鈕,你應該看到您的項目名稱的選項,這將啓動通過DOTNET CLI使用Kestrel您的應用程序。

其次,你需要定義兩個網址的紅隼聽,一個爲http和另一個爲https。這是通過簡單地通過兩個網址,與不同端口的UseUrls()方法main()完成:

var host = new WebHostBuilder() 
    .UseKestrel(options => { 
     options.UseHttps(certFile, certPass); 
    }) 
    .UseContentRoot(Directory.GetCurrentDirectory()) 
    .UseUrls("https://*:44388", "http://*:8080") 
    .UseStartup<Startup>() 
    .UseApplicationInsights() 
    .Build(); 

最後,如果你不使用默認的HTTPS端口(443),你需要指定哪些端口您也要kestrel重定向http請求。要做到這一點,只需重載AddRedirectToHttps()方法,通過傳遞status code以及您想要重定向的端口。我已使用狀態碼301永久重定向到https

var options = new RewriteOptions() 
.AddRedirectToHttps(301, 44388); 
0

我有類似的問題,使用.AddRedirectToHttps()。但我發現,它可能無法正確地將端口設置默認的SSL端口443

使用AddRedirectToHttpsPermanent(),而不是!因爲它會默認端口爲443

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
{ 
    // Redirects all HTTP requests to HTTPS 
    if (env.IsProduction()) 
    { 
     app.UseRewriter(new RewriteOptions() 
      .AddRedirectToHttpsPermanent()); 
    } 

    .... 
}