Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code when starting an ASP.NET MVC 4 Application

Tags:

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?

like image 656
Jim Blum Avatar asked Jan 17 '14 15:01

Jim Blum


People also ask

What is the starting point of MVC application?

The entry point for every MVC application begins with routing. After the ASP.NET platform has received a request, it figures out how it should be handled through the URL Routing Module.


2 Answers

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.

like image 64
John H Avatar answered Oct 05 '22 19:10

John H


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

like image 28
bedane Avatar answered Oct 05 '22 19:10

bedane