2013-02-06 17 views
4

我需要使用HTTPS註冊頁面的HTTP其他地方。我寫了下面的代碼在Global.asax中:如何在URL中使用HTTP替換HTTPS?

protected void Application_BeginRequest(object sender, EventArgs e) 
{ 
    var currentUrl = System.Web.HttpContext.Current.Request.Url; 
    if (currentUrl.AbsoluteUri.Contains("Registration")) 
    { 
     if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase)) 
     { 
      //build the secure uri 
      var secureUrlBuilder = new UriBuilder(currentUrl); 
      secureUrlBuilder.Scheme = Uri.UriSchemeHttps; 
      //use the default port. 
      secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString()); 
      //redirect and end the response. 
      System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString()); 
     } 
    } 
} 

這工作正常訪問註冊頁面,但是當我訪問其他網頁的方案不切換回HTTP。

+0

的replaceAll ???? –

+0

http://stackoverflow.com/questions/2560615/redirect-away-from-https-with-asp-net-mvc-app – Joe

回答

9

請在Global.asax中頁面添加以下代碼。

protected void Application_BeginRequest(object sender, EventArgs e) 
    { 
     var currentUrl = System.Web.HttpContext.Current.Request.Url; 
     if (currentUrl.AbsoluteUri.Contains("Registration")) 
     { 
      if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase)) 
      { 
       //build the secure uri 
       var secureUrlBuilder = new UriBuilder(currentUrl); 
       secureUrlBuilder.Scheme = Uri.UriSchemeHttps; 
       //use the default port. 
       secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString()); 
       //redirect and end the response. 
       System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString()); 
      } 
     } 
     else if(currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase)) 
     { 
       var secureUrlBuilder = new UriBuilder(currentUrl); 
       secureUrlBuilder.Scheme = Uri.UriSchemeHttp; 
       secureUrlBuilder.Port = 80; 
       System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString()); 

     } 
    }