1

our site address is like "http://members.XXX.XX", so I want to redirect to the "https://members.XXX.XX" no matter user type "members.XXX.XX" or "http://members.XXX.XX", here is my code, and i put it in the default.aspx

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsSecureConnection == false)
        {
            Response.Redirect(Request.Url.ToString().Replace("http://", "https://"));
        }

        if (!Request.Url.ToString().StartsWith("http://") || !Request.Url.ToString().StartsWith("https://"))
            Response.Redirect("https://" + Request.Url.ToString());

        Response.Redirect("~/pages/login.aspx");
    }

which doesn't work, anyone can help? many thanks

Edit: We didn't do that in IIS because we instored the ELMAH which is a error logging system. My coworker said if we did that the ELMAH wouldn't work

3
  • Why the code above does not work? Commented Jun 27, 2012 at 17:27
  • @WiktorZychla have no idea, typed members.XXX.XX which didn't redirect to https Commented Jun 27, 2012 at 17:38
  • @WiktorZychla I don't have SSL on my computer, but the url do redirect to localhost..., and can't display. Mark's method do solve my problem though Commented Jun 27, 2012 at 18:06

2 Answers 2

2

Instead of doing it in code simply let IIS handle it for you.

IIS7
Require ssl via IIS and capture the error code 403.4 to do the redirect for you. Step by step guide "IIS7 Redirect HTTP to HTTPS"

IIS6
You can create a redirect site that runs on port 80 to handle your redirect to https. Read more about it "How to Force Redirection From HTTP to HTTPS on IIS 6.0".

Sign up to request clarification or add additional context in comments.

2 Comments

We tried and my coworker said that will make ELMAH (a error logging system) disabled, so..
I currently have ELMAH setup and have the redirect in place. (I am using the basic configuration with elmah) I simply browse to the site at https://localhost/elmah.axd and everything works fine.
1

You can add to Global.asax

    protected void Application_BeginRequest()
    {

        if (!Context.Request.Url.AbsoluteUri.Contains("localhost") && !Context.Request.IsSecureConnection)
            Response.Redirect(Context.Request.Url.ToString().Replace("http:", "https:"));
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.