【问题标题】:Execute code when starting an ASP.NET MVC 4 Application启动 ASP.NET MVC 4 应用程序时执行代码
【发布时间】:2014-01-17 15:39:53
【问题描述】:

我想在我的应用程序启动时执行一些代码

   if (!WebMatrix.WebData.WebSecurity.Initialized){
           WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);

项目中有一个文件夹App_start,但是我没有找到任何可以添加此代码的文件。你知道是否有一个特定的文件有这个目的吗?

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

将您的代码放在类中的静态方法中。

public static class SomeStartupClass
{
    public static void Init()
    {
        // whatever code you need
    }
}

将其保存在App_Start。现在将其添加到 Global.asax,以及 MVC 在此处初始化的其他代码:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterAuth();

    SomeStartupClass.Init();
}

现在你的启动代码已经很好地分离了。

【讨论】:

  • 我遇到了下一个问题:Startup 的 Configuration 方法每次都会执行,当用户向 Web 应用程序发送请求时(调用控制器的方法)。但是当我启动应用程序时,我只需要执行一次我的方法
【解决方案2】:

这种启动代码通常放在Application_Start()方法中,Global.asax.cs文件

【讨论】:

    【解决方案3】:

    在 Global.asax 中使用以下内容:

    protected void Application_Start(object sender, EventArgs e)
    {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 2011-05-06
      • 2014-02-10
      相关资源
      最近更新 更多