开发者

Problem using context in global.asax file

开发者 https://www.devze.com 2023-03-24 13:41 出处:网络
I have user global.asax and I have write this code in my ASP.NET application : <%@ Application CodeBehind=\"Global.asax.cs\" Language=\"C#\" %>

I have user global.asax and I have write this code in my ASP.NET application :

    <%@ 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>

but it gives me this :

"Request is not available in this context"


From http to https you need to make redirect.

The main reason the RewritePath is not working is because the http and https work on different ports. Also the Application Start is not the place to call this thinks. The BeginRequest is the one.

So if you like to change all the request automatically to https, use this code.

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
}

You can also use this module to make this switching automatically.


Request is not available in Application_Start, it's too early.
You'll want to rewrite the path in Application_BeginRequest, see http://msdn.microsoft.com/en-us/library/sa5wkk6d.aspx for an example.

0

精彩评论

暂无评论...
验证码 换一张
取 消