本文介绍了asp.net C#重定向从http到https的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在我的code我想检测是否我的登录页面是被称为HTTP,并将其重定向到https。

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

我知道有非code方法对皮肤这只猫,但令人沮丧的技术reasosn我被逼到在code这样做。

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);
            }

于是,我放下这在我的Page_Load(...),以确保我的调试器使用IIS实,不VS2008s IIS,并创下调试。

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

在矿井调试器,华尔兹一起打
的Response.Redirect(HTTPS://localhost/StudentPortal3G/AccessControl/AdLogin.aspx),
按F5键...

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

获得互联网Explorere无法显示该网页,网址是HTTP,HTTPS不是。
没有收到信息的错误...同样的事情发生不是在调试器中运行。

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.

所以我缺少什么?它不会出现是火箭科学,我已经看到了类似的code对很多博客......

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.

推荐答案

我会做一个!Request.IsLocal ,以及确保我没有调试,但如果你正在使用IIS的一个真实实例与应用证书调试时,不应该是一个问题。

I'd do a !Request.IsLocal as well to make sure that I'm not debugging, though if you're using a real instance of IIS with a cert applied when debugging that shouldn't be an issue.

if (!Request.IsLocal && !Request.IsSecureConnection)
{
    string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
    Response.Redirect(redirectUrl, false);
    HttpContext.ApplicationInstance.CompleteRequest();
}

请注意:这个答案假定控制器,其中的HttpContext 是保存当前上下文属性中的MVC环境。如果你足够倒霉的仍然在使用的WebForms或正在引用你需要使用一个退化的方式上下文 HttpContext.Current.ApplicationInstance.CompleteRequest()

Note: This answer assumes an MVC context within a Controller where HttpContext is a property holding the current context. If you're unlucky enough to still be using WebForms or are referencing the context in a degenerate way you will need to use HttpContext.Current.ApplicationInstance.CompleteRequest().

请注意:我已经更新这是与推荐的模式相一致根据的。

Note: I've updated this to be consistent with the recommended pattern to terminate the request according to the framework documentation.

当您使用此方法在页面处理程序终止的请求
  一个页面,并开始为另一个页面的新的请求,设置endResponse为
  假的,然后调用CompleteRequest方法。如果指定true
  对于endResponse参数,这个方法调用End方法
  原来的要求,这将引发ThreadAbortException异常
  当它完成。此异常对网络产生不利影响
  应用程序的性能,这就是为什么通过假的
  建议endResponse参数。欲了解更多信息,请参阅
  最终方法。

这篇关于asp.net C#重定向从http到https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:32