2011-10-26 61 views
1

在我們的Web解決方案中,如果我們的environmentmode設置爲生產,我們希望在連接不安全的情況下將用戶重定向到安全連接。http到https應用範圍內的重定向

如果可能的話,我真的很想避免因爲有數百頁而不得不在每一頁上打這個檢查。

有沒有辦法在global.asax中完成這項工作?還是其他應用範圍的解決方案?

我已經試過如下:

if (SettingsHandler.EnvironmentMode == EnvironmentModes.Production) 
{ 
    if (!HttpContext.Current.Request.IsSecureConnection) 
    { 
     HttpContext.Current.Response.Redirect("https://<obscured>"); 
    } 
} 
在begin_request事件

它設法檢測連接是否安全但重定向失敗,並且我得到一個通用的「頁面無法顯示」錯誤頁面。在客戶端瀏覽器中,url不會被轉換,它只會停留在起始頁面上,就像響應被破壞或服務器出於某種原因拒絕提供它。

任何幫助將不勝感激。

求助: 看到我在接受的答案的最後一個評論,爲什麼我接受它。

+0

聽起來很有趣,你可以把Fiddler放在上面,看看服務器是否返回302重定向頭?也可能Response.End後重定向。 – danswain

+0

@danswain服務器在我設法修復它之前沒有返回任何內容。這是一個客戶端錯誤,顯示該頁面無法顯示。 –

回答

0

你可以通過IIS來做到這一點。本頁顯示如何:http://www.sslshopper.com/iis7-redirect-http-to-https.html

另外,您可以使用global.asax - 只需將您的代碼放入global.asax中的Application_BeginRequest事件即可。

順便說一句我測試了這段代碼,它引起了任何請求到我的網站通過ssl重定向到谷歌 - 我懷疑你的重定向可能在try catch中。如果是的話記得要使用語法:

Response.Redirect("site",true); 

這裏是爲我工作的代碼: -

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.SessionState; 

namespace repeater 
{ 
    public class Global : System.Web.HttpApplication 
    { 

     protected void Application_Start(object sender, EventArgs e) 
     { 

     } 

     protected void Session_Start(object sender, EventArgs e) 
     { 

     } 

     protected void Application_BeginRequest(object sender, EventArgs e) 
     { 
      Response.Redirect("https://www.google.com"); 
     } 

     protected void Application_AuthenticateRequest(object sender, EventArgs e) 
     { 

     } 

     protected void Application_Error(object sender, EventArgs e) 
     { 

     } 

     protected void Session_End(object sender, EventArgs e) 
     { 

     } 

     protected void Application_End(object sender, EventArgs e) 
     { 

     } 
    } 
} 

看它是否簡化到爲你工作?

+0

如果您不屑於閱讀我的問題,您會發現後面的解決方案正是我所嘗試的。謝謝,雖然我會閱讀你發佈的鏈接。 –

+0

嗯,我很想知道你爲什麼會得到一個錯誤 - 你沒有嘗試抓住它嗎? –

+0

它不會拋出錯誤,頁面只是不顯示/傳遞與該重定向。 –

0

您可以使用iis url rewrite模塊進行此操作。

只需在<system.webServer>部分的web.config中添加以下內容即可。

<rewrite> 
    <rules> 
    <rule name="HTTP to HTTPS redirect" enabled="true" stopProcessing="true"> 
     <match url="(.*)"/> 
     <conditions> 
     <add input="{HTTPS}" pattern="off" ignoreCase="true"/> 
     </conditions> 
     <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}"/> 
    </rule> 
    </rules> 
</rewrite>