Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace HTTPS with HTTP in a URL?

I need to use https on registration pages and http everywhere else. I wrote the following code in 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());
        }
    }
}

This is working fine for visiting registration pages, but the scheme doesn't switch back to http when I visit other pages.

like image 402
Kartik Patel Avatar asked Jan 15 '23 07:01

Kartik Patel


1 Answers

Please add the following code in Global.asax Page.

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

        }
    }
like image 85
Kartik Patel Avatar answered Jan 21 '23 13:01

Kartik Patel