24

I want when my application starts, to execute some code

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

There is a folder App_start at the project, but I didn't find any file that I can add this code. Do you know if there is a specific file that has this purpose?

RBT
  • 24,161
  • 21
  • 159
  • 240
Jim Blum
  • 2,656
  • 5
  • 28
  • 37
  • 1
    Have you tried the `Application_Start` method of Global.asax.cs? – anar khalilov Jan 17 '14 at 15:42
  • Related post - [How to run a method in ASP.net MVC only once when application Load Without calling it from Application_Start()](https://stackoverflow.com/q/32392337/465053) – RBT May 06 '21 at 10:44

3 Answers3

41

Put your code in static method inside a class.

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

Save that in App_Start. Now add it to Global.asax, along with the other code MVC initialises here:

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();
}

Now your startup code is separated nicely.

Guido Preite
  • 14,905
  • 4
  • 36
  • 65
John H
  • 14,422
  • 4
  • 41
  • 74
  • 1
    I've faced with the next problem: Startup's Configuration method executes every time, when user sends request to Web application (call controller's method). But I need to execute my method just only once, when I start application – Vitaliy Mar 02 '18 at 16:24
30

This kind of startup code typically goes in the Application_Start() method, Global.asax.cs file

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
bedane
  • 1,129
  • 11
  • 13
3

Use the following in the Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
Joe Ratzer
  • 18,176
  • 3
  • 37
  • 51