【问题标题】:Where is the Global.asax.cs file?Global.asax.cs 文件在哪里?
【发布时间】:2011-09-11 09:44:34
【问题描述】:

我正在使用 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>

这很好。但是 Global.asax.cs 文件在哪里?

谢谢

【问题讨论】:

标签: c# asp.net .net visual-studio-2008 global-asax


【解决方案1】:

无法正常创建;您需要自己添加。

通过

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

你需要添加一个类

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

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

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

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

App_Code 中的 Global.cs 将如下所示:-

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
}

【讨论】:

  • 我收到错误消息“'application' 指令不支持 'inherit' 属性。”
  • @RahulJain,它是Inherits 不继承。你检查过你的拼写吗?否则你使用的是哪个框架版本?
  • 描述中有错字 (Glabal.cs) - 我无法编辑这篇文章,因为编辑内容少于 6 个字符。
【解决方案2】:

那是因为您创建了一个网站而不是一个 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()
        {
        }
    }
}

【讨论】:

  • 那么获取global.asax和global.asax.cs文件的方法是什么?
  • 如果您使用Web应用程序模型,那么您将能够获得单独的cs文件。
  • @apurva;更新的答案,你也可以在网站上实现:)
  • 我收到编译时错误无法加载类型“全局”。我已经更新了问题
  • 我收到“无法加载类型 XXXX”错误。我把它作为一个网站项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 2019-04-10
  • 2022-01-16
  • 2017-09-04
  • 2019-09-24
  • 2014-04-02
相关资源
最近更新 更多