asp.net c# redirecting from http to https

2019-01-10 09:48发布

So in my code I want to detect if my login page is being called http, and redirect it to https.

I know there are non code ways to skin this cat, but for frustrating technical reasosn I'm backed into doing it in code.

            if (!Request.IsSecureConnection)
            {
                string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
                Response.Redirect(redirectUrl);
            }

So I drop this in my Page_Load(...), make sure my debugger uses real IIS, not VS2008s IIS, and hit debug.

Inthe debugger, waltz along, hit Response.Redirect("https://localhost/StudentPortal3G/AccessControl/AdLogin.aspx"), hit f5.

Get "Internet Explorere Cannot Display the webpage, url is HTTP, not HTTPS. Not getting an informative error... same thing happens not running in the debugger.

So what am I missing? it does not appear to be rocket science, I've seen similar code on lots of blogs...

What am I doing wrong? I figure it has to be a totally obvious Rookie mistake, but I'm not seeing it.

9条回答
别忘想泡老子
2楼-- · 2019-01-10 10:15

I would also suggest tvalfonsso's solution, but with a small modification in case you have some url rewriting (RawUrl differs from Url)

    if (SPPage == SPPages.StartAutotrading && !Request.IsLocal && !Request.IsSecureConnection)
        {
            string redirectUrl = (Request.Url.ToString().Replace(Request.Url.PathAndQuery.ToString(), "") + Request.RawUrl).Replace("http:", "https:");
            Response.Redirect(redirectUrl);
        }
查看更多
神经病院院长
3楼-- · 2019-01-10 10:25

In my opinion the following is the best all-round approach.

Three reasons

  1. It works for both MVC and Web API as it is done at IIS level.
  2. It does not effect local / debug settings. (permanent redirect can mess you around when debugging non https sites on your pc).
  3. Uses a permanent redirect, so all future requests will automatically go to https

Simply add the following to your <system.webServer> section in your 'Web.config' for your project.

 <system.webServer>
 ....

 <rewrite>
  <rules>
    <rule name="HTTP to HTTPS redirect" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
    </rule>
  </rules>
  <outboundRules>
    <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
      <match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" />
      <conditions>
        <add input="{HTTPS}" pattern="on" ignoreCase="true" />
      </conditions>
      <action type="Rewrite" value="max-age=31536000" />
    </rule>
  </outboundRules>
</rewrite>
</system.webServer>
查看更多
我只想做你的唯一
4楼-- · 2019-01-10 10:25

On my development environment, I like to have a separate publish directory with IIS installed with a self signed cert, which is different form my code directory without a cert that I debug directly inside of Visual Studio. In this scenario !Request.IsLocal isn't ideal because it doesn't work anywhere on your development environment, even in the IIS directory with the cert. I prefer this:

if (!IsPostBack && !HttpContext.Current.IsDebuggingEnabled) 
{
    // do http->https and https->http redirection here
}

HttpContext.Current.IsDebuggingEnabled is based on the value of compilation debug="true/false" in your web.config. I have it set to true in my code directory, and false in my publish directory when I need to test http and https redirection locally.

I add in the IsPostBack simply to make it (slightly) more efficient by skipping the extra ssl checking when not needed.

查看更多
登录 后发表回答