如何在URL中用HTTP替换HTTPS?

时间:2013-02-06 09:34:18

标签: http c#-4.0 web-applications https global-asax

我需要在注册页面上使用https,在其他地方使用http。我在global.asax中编写了以下代码:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var currentUrl = System.Web.HttpContext.Current.Request.Url;
    if (currentUrl.AbsoluteUri.Contains("Registration"))
    {
        if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps,  StringComparison.CurrentCultureIgnoreCase))
        {
            //build the secure uri 
            var secureUrlBuilder = new UriBuilder(currentUrl);
            secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
            //use the default port.  
            secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString());
            //redirect and end the response. 
            System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
        }
    }
}

这适用于访问注册页面,但当我访问其他页面时,该方案不会切换回http。

1 个答案:

答案 0 :(得分:9)

请在Global.asax页面中添加以下代码。

  protected void Application_BeginRequest(object sender, EventArgs e)
    {
        var currentUrl = System.Web.HttpContext.Current.Request.Url;
        if (currentUrl.AbsoluteUri.Contains("Registration"))
        {
            if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
            {
                //build the secure uri 
                var secureUrlBuilder = new UriBuilder(currentUrl);
                secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
                //use the default port.  
                secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString());
                //redirect and end the response. 
                System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
            }
        }
        else if(currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
        {
                var secureUrlBuilder = new UriBuilder(currentUrl);
                secureUrlBuilder.Scheme = Uri.UriSchemeHttp;
                secureUrlBuilder.Port = 80;
                System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());

        }
    }