2013-02-06 2 views
4

Мне нужно использовать https на страницах регистрации и http везде. Я написал следующий код в global.asax:Как заменить HTTPS на HTTP в URL?

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()); 

     } 
    } 
Смежные вопросы