【问题标题】:Problem using context in global.asax file在 global.asax 文件中使用上下文的问题
【发布时间】:2011-10-16 10:37:00
【问题描述】:

我有用户 global.asax,我已经在我的 ASP.NET 应用程序中编写了这段代码:

    <%@ Application CodeBehind="Global.asax.cs" Language="C#" %>

<script RunAt="server">
    public void Application_Start()
    {
        string str = Context.Request.Url.AbsoluteUri.Replace("http", "https");
        Context.RewritePath(str);
    }
</script>

但它给了我这个:

"Request is not available in this context"

【问题讨论】:

标签: asp.net global-asax


【解决方案1】:

从http到https需要重定向。

RewritePath 不起作用的主要原因是 http 和 https 在不同的端口上工作。此外,应用程序启动也不是调用这个想法的地方。 BeginRequest 就是其中之一。

因此,如果您想将所有请求自动更改为 https,请使用此代码。

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;
    string cTheFile = HttpContext.Current.Request.Path;
    string sExtentionOfThisFile = System.IO.Path.GetExtension(cTheFile);
    if (sExtentionOfThisFile.Equals(".aspx", StringComparison.InvariantCultureIgnoreCase))
    {
        if (!app.Context.Request.IsSecureConnection)
        {
            Response.Redirect(app.Context.Request.RawUrl.Replace("http://", "https://"), true);
            return;
        }
    }

    // rest of your code here and below
}

你也可以用这个 module to make this switching automatically.

【讨论】:

    【解决方案2】:

    请求在Application_Start 中不可用,为时过早。
    您需要重写Application_BeginRequest 中的路径,例如,请参阅http://msdn.microsoft.com/en-us/library/sa5wkk6d.aspx。

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2015-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 2020-01-18
      • 2022-11-20
      相关资源
      最近更新 更多