cdub
cdub

Reputation: 25751

Redirects with Global.asax file in C#

I have added the following code to my Global.asax file:

 <%@ Application Language="C#" %>

 <script runat="server">

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    if (ConfigurationManager.AppSettings["IsReviewServer"] == "Yes")
    {
        if (!Request.IsSecureConnection)
        {
            string path = string.Format("https{0}", Request.Url.AbsoluteUri.Substring(4));

            Response.Redirect(path);
        }
    }
}

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

}

etc.....

But my BeginRequest function just gets ignored. How do I redirect my entire application from http: to https:?

Upvotes: 0

Views: 7234

Answers (1)

James Johnson
James Johnson

Reputation: 46077

If you're using a master page or a base class, I would put your logic there. Global events shouldn't be relied upon for logic like this.

Put the logic in Page_Load (or earlier in the lifecycle) of the master page or base class like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (ConfigurationManager.AppSettings["IsReviewServer"] == "Yes") 
    { 
        if (!Request.IsSecureConnection) 
        { 
            string path = string.Format("https{0}", Request.Url.AbsoluteUri.Substring(4)); 

            Response.Redirect(path); 
        } 
    } 
}

You could do the above at another point in the lifecycle if you wanted too, like PreLoad or PreRender.

Using global events

If you're going to use a global event, I would actually use Application_EndRequest, because it gets called on every request so the application can clean up resources.

Upvotes: 1

Related Questions