Thursday, August 27, 2015

How to add a Global.asax.cs to a website

Global.asax is the asp.net application file. It is an optional file that handles events raised by ASP.NET or by HttpModules. It is used to handle server aoplication-level and session-level events.Fo example, used for application and session start/end events and for global error handling. When used, it should be in the root of the website. Only one Global.asax can be found in any project/website.

When creating a web application project, you have a Global.asax and its corresponding Global.asax.cs. However, in a web application the class (Global.asax.cs) cannot be created.

The created Global.asax starts with
<%@ Application  Language="C#" %>
And looks like the following image

To add Global.asax.cs
Choose your solution=> Add => Class
Save it as Global.asax.cs,
It must be saved in App_Code to be compiled correctly.

Even if you didn't save it to App_code, you will get the following warning:


Next cut code (without the tags, just c# code) from Global.asax and paste it to Global.asax.cs, as follows:

public class Global : System.Web.HttpApplication
{
    protected void Application_Start()
    {
       
    }
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occur
    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started.
    }
}

And in Global.asax leave only this line:
<%@ Application Codebehind="Global.asax.cs" Inherits="Global" Language="C#" %>


Thanks,
Nerdy Geeky J!

2 comments:

  1. Replies
    1. It is a file that can be added once only in your project. It is where you can handle application level events and session level events.

      For example what you want to happen the first time an application starts, or when it ends, or when an error occurs.

      Delete