Global.asax.cs文件在哪里?

apu*_*rva 45 .net c# asp.net visual-studio-2008 global-asax

我正在使用VS 2008.我已经从File-> New-> Website-> Asp.net Website创建了一个新的Asp.net网站项目.

现在我想将Global.asax和.cs文件添加到项目中.所以我右键单击项目 - >添加新项目 - >全局应用程序类.然后我点击了添加按钮.

Global.asax文件添加了内容,如下

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

 <script runat="server"%>

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

    }

    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }

    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }

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

    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }

</script>
Run Code Online (Sandbox Code Playgroud)

这可以.但是Global.asax.cs文件在哪里?

谢谢

Waq*_*aja 53

它没有正常创造; 你需要自己添加它.

加入后Global.asax通过

  • 右键单击您的网站 - > 添加新项 - > 全局应用程序类 - >添加

你需要添加一个类

  • 右键单击App_Code - > 添加新项 - > - >将其命名为Global.cs - > Add

继承新生成的System.Web.HttpApplication并复制创建的所有方法 Global.asax,Global.cs并将继承属性添加到Global.asax文件中.

你的Global.asax将如下所示: -

<%@ Application Language="C#" Inherits="Global" %>
Run Code Online (Sandbox Code Playgroud)

Global.csApp_Code看起来像这样: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

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

    }
    /// Many other events like begin request...e.t.c, e.t.c
}
Run Code Online (Sandbox Code Playgroud)


Muh*_*tar 31

那是因为您创建了一个Web站点而不是Web应用程序.这些cs/vb文件只能在Web应用程序中看到,但在网站中您不能拥有单独的cs/vb文件.

编辑:在网站上你可以添加一个cs文件行为,如..

<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>

~/Global.asax.cs:

namespace ApplicationName
{
    public partial class MyApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)