I am trying to redirect from secure (https) to http when user login. It redirects fine but for some reason its keeping the https.
Response.Redirect(RedirectPath)
RedirectPath contains fully qualified URL including http.
for example RedirectPath = "http://www.mydomain.com"
but it redirects to the https://www.mydomain.com
I redirect by running the following on Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!Request.IsLocal && !Request.IsSecureConnection)
{
var ub = new UriBuilder(Request.Url);
ub.Scheme = Uri.UriSchemeHttps;
ub.Port = -1; // use default port for scheme
Response.Redirect(ub.Uri.ToString(), true);
return;
}
}
}
You can similarly go from https to http by setting the Scheme to UriSchemeHttp if IsSecureConnection is true.
Here's my 2 cents...
Make a simple attribute class like this:
public class ForceSSL : System.Attribute{
public bool Enabled;
public ForceSSL(bool _enabled)
Enabled = _enabled; }
Next, create a base class for your page(s) to inherit from. Inside the base class override the OnPreInit event as such (building from the example above @ Druid):
protected override void OnPreInit(EventArgs e)
{
if (!Request.IsSecureConnection)
{
var _sslAttr = this.GetType().GetCustomAttributes(true).Where(at => (at as ForceSSL) != null).FirstOrDefault();
if (_sslAttr != null)
{
if ((_sslAttr as ForceSSL).Enabled)
{
var ub = new UriBuilder(Request.Url);
ub.Scheme = Uri.UriSchemeHttps;
ub.Port = -1;
Response.Redirect(ub.Uri.ToString(), true);
return;
}
}
}
base.OnPreInit(e);
}
Now just make your pages inherit from your base class and place the attribute [ForceSSL(true)] at the top of each page that you want to access via SSL.
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