How to run events in global.asax.cs

614 Views Asked by At

I use Visual Studio 2019 to create a new webforms project. I write a Session_Start event in the Global.asax.cs, but it never fires!

Here is some code - Global.asax

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

Global.asax.cs:

namespace webApp
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            Application["test"] = "123";
        }

        void Session_Start(object sender, EventArgs e)
        {
            Session["test"] = "123";
        }
    }
}

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    string test = Application["test"].ToString();
    string test1 = Session["test"].ToString();
}

When the program runs into the Page_Load of Default.aspx.cs, it will throw an exception: System.NullReferenceException

What can I do?

0

There are 0 best solutions below