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.
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());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With