首页 > 解决方案 > 如何在 global.asax.cs 中运行事件

问题描述

我使用 Visual Studio 2019 创建一个新的 webforms 项目。我在 中写了一个Session_Start事件Global.asax.cs,但它永远不会触发!

这是一些代码 -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";
        }
    }
}

默认.aspx.cs

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

当程序运行到Page_LoadofDefault.aspx.cs时,会抛出异常:System.NullReferenceException

我能做些什么?

标签: c#asp.netwebformscode-behindglobal-asax

解决方案


推荐阅读