Understanding Web API 2 Request Life cycle

 23-Nov-2018   nityaprakash     WebAPI  RESTful  life-cycle  Controller    Comments  0

In this article I am going to explain how Web API 2.0 lifecycle works. This is the process by which Web API dispatches requests, which is the sequence of steps by which an incoming HttpRequestMessage object is processed to produce an HttpResponseMessage that can be sent to the client.

Request Dispatching

Classes which coordinates the way Web API handles the HTTP requests, known as message handlers. Each handler inherits from HttpMessageHandler class, which define one important method, which derived classes are required to implement. This can be found in System.Net.Http namespace.


protected internal override Task SendAsync(
	HttpRequestMessage request,
	CancellationToken cancellationToken
	)

These default message handlers are gatekeepers to the WebAPI process. Once request come to WebAPI message handler below handlers are executed in sequence:

  • HttpServer : This is first message handler in dispatch process.
  • HttpRoutingDispatcher : The second messgae handler, which generate routing data for the request.
  • HttpControllerDispatcher:Third and final message handler which select, activate and executes a controller to create HttpResponseMessage.

HttpServer Class

HttpServer class is the contact point between hosting environment and WebAPI. It receives HttpRequestMessage and prepare it for use in Web API and passes it to the next message handler in the chain. Preparation includes followings:

  • Assoiciating sequrity principal to the request.
  • Createing HttpRequestContext object
  • Setting up class which deal with error in HttpResponseMessage.

HttpServer class is instanciated by GlobalCoonfiguration during configuration phase. It also tell which is the next handler. It returns DefaultHandler and DefaultServer and values returned cannont be changed.

HttpRoutingDispatcher Class

This is second message handler in the chain of handler. It has only one responsibility is that extracting routing data and rount data from the HttpRequestMessage and assigning the values to HttpRequestContext.RouteData properties. It exttract folllowing informations:

  • The name of Controller
  • The name of action method
  • Values that can be used for parameter binding.

It doesn't generate any HttResponseMessage or execute/create Controller object. It just gether the information.

HttpControllerDispatcher class

This is final message handler and responsible for locating controller class, creating instance and executing to produce HttpResponseMessage object. This message handler is rely on sevelral components to achive this functionality:

Selecting Controller

The HttpControllerDispatcher delegate task to the class which implements IHttpControllerSelector. The name of default implemntation is DefaultControllerSelector


namespace System.Web.Http.Dispatcher {

	public interface IHttpControllerSelector 
	{
		IDictionary GetControllerMapping();
		
		HttpControllerDescriptor SelectController(HttpRequestMessage request);
	}
}

As interface sugest that it Create the list of all controllers in the application at startup of the application and cach it for lifecycle of the application (AppPool). SelectController method is used to get the instance of HttpControllerDescriptor which contains important information about the controller:

  • Configuration
  • ControllerName
  • ControllerType
  • CreateController(request)
  • GetCustomAttributes()
  • GetFilters()

Controller selector delegate to IHttpControllerTypeResolver to get type information about the controller.


namespace System.Web.Http.Dispatcher {

	public interface IHttpControllerTypeResolver 
	{
		ICollection GetControllerTypes(IAssembliesResolver assembliesReolver);
	}
}

The interface IAssembliesResoler implemented by DefaultAssembliesResolver class and it resolve all assemblies in the application. Once DefaultHtttpControllerTypeResolver has all informaion, it inspects the classes in the assemblies and resolve all controllers with classes having following charactrisitcs:

  • They are the classes that implements the IHttpController interface.
  • the name of the class post fix with Controller
  • The class is public and abstract.

Instantiating the Controller

Once Controller is resolved and get object HttpControllerDescriptor it calls the CreateController method which instantiate the controller object. Which in turn delegate creation process to implementation of IHttpControllerActivator class.


namespace System.Web.Http.Dispatcher {

	public interface IHttpControllerActivator 
	{
		IHttpController Create(HttpRequestMessage request,
			HttpControllerDescriptor controllerDescriptorm, 
			Type controllerType
			);
	}
}

It has DefaultHttpControllerActivator class which perform following task in order to create Controller instance:

  • Try to get an instance of the controller type from the dependency resolver
  • Create an instance of the controller by invoking a parameterless construcotr.

If You have controller with parameterized contructor in that case you have specify in configuration that how to create object of parameter. There is another way to handle this situation is create custom implementation of IHttpControllerActivator.

Executing the Controller

Once instance of controller is created, it will execute it by calling ExecuteAsync method.


namespace System.Web.Http.Dispatcher {

	public interface IHttpController 
	{
		Task ExecuteAsync(HttpControllerContext context, CancellationToken token);
	}
}

The HttpControllerDispatcher create the object of HttpControllerContext and store information which require controller to execute the request. The HttoControlerContext store the following information:

  • Configuration
  • Controller
  • ControllerDescriptor
  • Request
  • RequestContext
  • RouteData

We can summarize this complete process in below diagram to understand and remember easily.

Conclusion

In this article, I tried to explain the steps involve in executing a Web API request. Once host knows that it WebAPI request it starts with HttpServer and create HttpRequestContext object and pass message to next handler in the chain called HttpRoutingDispatcher. It just collect routing and route data from the URL and pass the handle to HttpControllerDispatcher. Which will resolve the controller, create object and execute it.


Nitya Prakash Sharma has over 10 years of experience in .NET technology. He is currently working as Senior Consultant in industry. He is always keen to learn new things in Technology and eager to apply wherever is possible. He is also has interest in Photography, sketching and painting.

My Blog
Post Comment

COMMENTS