Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Redirecting from Https to Http

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

like image 698
salman Avatar asked Jan 21 '26 19:01

salman


2 Answers

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.

like image 181
Druid Avatar answered Jan 23 '26 11:01

Druid


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.

like image 25
Dreamer Avatar answered Jan 23 '26 12:01

Dreamer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!