ASP.NET MVC Controller Lifecycle

前端 未结 3 470
醉梦人生
醉梦人生 2020-11-27 17:48

It\'s my understanding that the constructor for a controller is not called during each web request. Assuming this is true, what is the lifecycle of a controller? Is is \"con

3条回答
  •  暖寄归人
    2020-11-27 18:27

    A controller is created for every request you do. Lets take an example.

       public class ExampleController : Controller{
               public static userName;
    
                public void Action1(){//do stuff}
                public void Action2(){//do stuff}
                public void AssignUserName(string username){
                     userName = username;
    
                }
               public string GetName(){ return userName;}
    
    
       }
    

    Now you can call the controller from the view passing a username. Don't hope to get the userName you set in the next request. it will return null. Thus for every request a new controller is created. You don't instantiate a controller anywhere in MVC like you instatiate an object from a class. Simply you don't have controller object memory pointer to call it as you do with other objects.

    Go to this link. There is a good explanation on lifecycle of MVC controller.

    ASP.Net MVC - Request Life Cycle

提交回复
热议问题