http - 如何将 URL 中的 HTTPS 替换为 HTTP?

标签 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。

最佳答案

请在 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());

        }
    }

关于http - 如何将 URL 中的 HTTPS 替换为 HTTP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14725686/

相关文章:

php - 画廊图片的想法

linux - 从使用 wget 重定向的页面获取文件

linux - 将curl请求转换成http请求?

.htaccess - 当我强行将 http 重定向到 https 时,它显示重定向了你太多次

c# - PLINQ 的性能比通常的 LINQ 差

c# - 从代码隐藏中获取重写的 url

javascript - 如何将 python pdfkit 与 python flask webapp 一起使用

c# - 具有继承 TPH 的 EF 4.1 Code First 复杂类型

java - maven webapp将jsp放在/WEB-INF/jsp

java - Spring Boot WebSecurityConfig LogoutSuccessURL 与 invalidSessionUrl