SlideShare uma empresa Scribd logo
1 de 31
ASP.NET MVC 4 Request Pipeline
Lukasz Lysik
ASP.NET MVC 4 Study Group
20/08/2013
ASP.NET MVC Request Pipeline
http://localhost/Controller/Action/1
Hello
World!
HTTP Modules and HTTP Handlers
(Not directly related to ASP.NET MVC but short
introduction will help understand further topics.)
An HTTP module is an assembly that is called on every
request made to your application.
An HTTP handler is the process (frequently referred to
as the "endpoint") that runs in response to a request
made to an ASP.NET Web application.
Source: http://msdn.microsoft.com/en-us/library/bb398986%28v=vs.100%29.aspx
HTTP Modules and HTTP Handlers
HTTP
Module 1
HTTP
Module 2
HTTP
Module 3
HTTP
Module 4
HTTP Handler
“HttpHandler is where the request train is headed. HttpModule is a station along the way.”
Source: http://stackoverflow.com/questions/6449132/http-handler-vs-http-module
Typical Uses
HTTP Modules
Security
Statistics and logging
Custom headers or
footers
HTTP Handlers
RSS feeds
Image server
Custom HTTP Modules
public class HelloWorldModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
application.EndRequest += (new EventHandler(this.Application_EndRequest));
}
private void Application_BeginRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write("<h1><font color=red> HelloWorldModule: Beginning of Request </font></h1><hr>");
}
private void Application_EndRequest(Object source, EventArgs e)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
context.Response.Write("<hr><h1><font color=red> HelloWorldModule: End of Request</font></h1>");
}
public void Dispose() { }
}
<configuration>
<system.web>
<httpModules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</httpModules>
</system.web>
</configuration>
Source: http://msdn.microsoft.com/en-us/library/ms227673%28v=vs.85%29.aspx
public interface IHttpModule
{
void Init(HttpApplication context);
void Dispose();
}
Custom HTTP Handlers
using System.Web;
public class HelloWorldHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
Response.Write("<html>");
Response.Write("<body>");
Response.Write("<h1>Hello from a synchronous custom HTTP handler.</h1>");
Response.Write("</body>");
Response.Write("</html>");
}
public bool IsReusable
{
get { return false; }
}
}
public interface IHttpHandler
{
bool IsReusable { get; }
void ProcessRequest(HttpContext context);
}
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.sample" type="HelloWorldHandler"/>
</httpHandlers>
</system.web>
</configuration>
Source: http://msdn.microsoft.com/en-us/library/ms228090%28v=vs.100%29.aspx
If you plan to write your own web framework this is good starting point.
Existing HTTP Modules and HTTP
Handlers
HTTP Modules and HTTP Handlers are registered in
.NET Framework’s Web.config:
c:WindowsMicrosoft.NETFrameworkv4.0.30319Configweb.config
Further info: http://programmer.lysik.pl/2013/08/asp-net-http-modules-and-http-handlers.html
ASP.NET MVC Request Pipeline
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
It all start with UrlRoutingModule.
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
HTTP Handler
HTTP
Module 1
HTTP
Module 2
UrlRoutingModule
RouteTable.Routes
MvcHandler
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
MvcApplication (Global.asax)
RouteTable.Routes
(System.Web.Routing)
System.Web.Mvc.RouteCollectionExtensions
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
Url IRouteHandler Defaults Constraints DataTokens
/Category/{action}/{id} PageRouteHandler … … …
/{controller}/{action}/{id} MvcRouteHandler … … …
… … … … …
RouteTable.Routes
(System.Web.Routing)RouteTable.Routes in fact contains:
Classes that implement IRouteHandler are not HTTP handlers! But they should return one.
System.Web.Mvc.MvcRouteHandler MvcHandler
System.Web.Routing.PageRouteHandler Page or UrlAuthFailureHandler
System.Web.WebPages.ApplicationParts.ResourceRouteHandler ResourceHandler
System.ServiceModel.Activation.ServiceRouteHandler AspNetRouteServiceHttpHandler
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
HTTP Handler
HTTP
Module 1
HTTP
Module 2
UrlRoutingModule
RouteTable.Routes
MvcHandler
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
UrlRoutingModule
1
2
3
4
RemapHandler tells IIS which HTTP handler we want to use.
RouteTable.Routes
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
1
RouteTable.Routes
(System.Web.Routing)
RouteCollection
public RouteData GetRouteData(HttpContextBase httpContext)
{
if (this.Count == 0) return (RouteData) null;
. . .
foreach (RouteBase routeBase in (Collection<RouteBase>) this)
{
RouteData routeData = routeBase.GetRouteData(httpContext);
if (routeData != null)
{
return routeData;
}
}
return (RouteData) null;
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteValueDictionary values = this._parsedRoute.Match(httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2)
+ httpContext.Request.PathInfo, this.Defaults);
RouteData routeData = new RouteData((RouteBase) this, this.RouteHandler);
if (!this.ProcessConstraints(httpContext, values, RouteDirection.IncomingRequest))
return (RouteData) null;
. . .
return routeData;
}
Route
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
HTTP Handler
HTTP
Module 1
HTTP
Module 2
UrlRoutingModule
RouteTable.Routes
MvcHandler
4
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
MvcHandler
Controller Builder
3. Call Execute on created Controller
2. Create Controller using ControllerFactory
1. Get ControllerFactory
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
MvcHandler
private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory)
{
. . .
string requiredString = this.RequestContext.RouteData.GetRequiredString("controller");
factory = this.ControllerBuilder.GetControllerFactory();
controller = factory.CreateController(this.RequestContext, requiredString);
if (controller != null)
return;
. . .
}
2
1
3
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
factory = this.ControllerBuilder.GetControllerFactory();
controller = factory.CreateController(this.RequestContext, requiredString);
2
ControllerBuilder
internal ControllerBuilder(IResolver<IControllerFactory> serviceResolver)
{
ControllerBuilder controllerBuilder = this;
IResolver<IControllerFactory> resolver = serviceResolver;
if (resolver == null)
resolver = (IResolver<IControllerFactory>) new SingleServiceResolver<IControllerFactory>(
(Func<IControllerFactory>) (() => this._factoryThunk()), (IControllerFactory) new DefaultControllerFactory()
{
ControllerBuilder = this
}, "ControllerBuilder.GetControllerFactory");
controllerBuilder._serviceResolver = resolver;
}
public class CustomControllerFactory : IControllerFactory
{
public IController CreateController(RequestContext requestContext, string controllerName)
{
. . .
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
IControllerFactory factory = new CustomControllerFactory();
ControllerBuilder.Current.SetControllerFactory(factory);
}
}
Custom Controller Factory
MvcHandler
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
Controller / ControllerBase
Dependency
Resolution
4. Call InvokeAction on action invoker.
3. Get action invoker.
2. Get action name from RouteData.
1. Call ExecuteCore
0. Execute being called by MvcHandler
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
3
ControllerBase
Controller : ControllerBase
protected override void ExecuteCore()
{
. . .
string requiredString = this.RouteData.GetRequiredString("action");
this.ActionInvoker.InvokeAction(this.ControllerContext, requiredString);
. . .
}
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
3
Controller : ControllerBase
protected virtual IActionInvoker CreateActionInvoker()
{
return (IActionInvoker) DependencyResolverExtensions.GetService<IAsyncActionInvoker>(this.Resolver)
?? DependencyResolverExtensions.GetService<IActionInvoker>(this.Resolver)
?? (IActionInvoker) new AsyncControllerActionInvoker();
}
Possible methods of replacing default
ActionInvoker:
• Assign to ActionInvoker property.
• Override CreateActionInvoker method.
• Use dependency injection.
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
6. Invoke action result
5. Invoke action
4. Bind models.
3. Invoke authorization filters.
2. Find action using descriptor
1. Get controller descriptor (reflection).
0. InvokeAction being called by Controller.ExecuteCore
ActionInvoker
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
ControllerActionInvoker : IActionInvoker
this.ActionInvoker.InvokeAction(this.ControllerContext, requiredString);
1
2
3
4
6
5
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
4
ControllerActionInvoker : IActionInvoker
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
6
ControllerActionInvoker : IActionInvoker
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
ViewResultBase
ViewResultBase
ViewResult PartialViewResult
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
ViewResult
PartialViewResult
1. Routing
2. Controller
execution
3. Action
execution
4. Result
execution
JsonResult
HttpStatusCodeResult
Questions?

Mais conteúdo relacionado

Mais procurados

An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
backdoor
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
vamsi krishna
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
Core web application development
Core web application developmentCore web application development
Core web application development
Bahaa Farouk
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
vamsi krishna
 

Mais procurados (19)

An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
Core web application development
Core web application developmentCore web application development
Core web application development
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 
Servlets
ServletsServlets
Servlets
 
Servlet
Servlet Servlet
Servlet
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 

Semelhante a ASP.NET MVC 4 Request Pipeline Internals

Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
Guy Nir
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe
 

Semelhante a ASP.NET MVC 4 Request Pipeline Internals (20)

Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
ASP.NET Internals
ASP.NET InternalsASP.NET Internals
ASP.NET Internals
 
Asp.net mvc
Asp.net mvcAsp.net mvc
Asp.net mvc
 
Developing ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller PatternDeveloping ASP.NET Applications Using the Model View Controller Pattern
Developing ASP.NET Applications Using the Model View Controller Pattern
 
Asp.Net Mvc
Asp.Net MvcAsp.Net Mvc
Asp.Net Mvc
 
Api RESTFull
Api RESTFullApi RESTFull
Api RESTFull
 
Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
ASP.NET MVC introduction
ASP.NET MVC introductionASP.NET MVC introduction
ASP.NET MVC introduction
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Introduction to Struts 1.3
Introduction to Struts 1.3Introduction to Struts 1.3
Introduction to Struts 1.3
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
ASP.NET MVC 2.0
ASP.NET MVC 2.0ASP.NET MVC 2.0
ASP.NET MVC 2.0
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 
Day7
Day7Day7
Day7
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
SoftServe - "ASP.NET MVC як наступний крок у розвитку технології розробки Web...
 
Asp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design PatternAsp.Net MVC Framework Design Pattern
Asp.Net MVC Framework Design Pattern
 
Solving anything in VCL
Solving anything in VCLSolving anything in VCL
Solving anything in VCL
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 

ASP.NET MVC 4 Request Pipeline Internals

  • 1. ASP.NET MVC 4 Request Pipeline Lukasz Lysik ASP.NET MVC 4 Study Group 20/08/2013
  • 2. ASP.NET MVC Request Pipeline http://localhost/Controller/Action/1 Hello World!
  • 3. HTTP Modules and HTTP Handlers (Not directly related to ASP.NET MVC but short introduction will help understand further topics.) An HTTP module is an assembly that is called on every request made to your application. An HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. Source: http://msdn.microsoft.com/en-us/library/bb398986%28v=vs.100%29.aspx
  • 4. HTTP Modules and HTTP Handlers HTTP Module 1 HTTP Module 2 HTTP Module 3 HTTP Module 4 HTTP Handler “HttpHandler is where the request train is headed. HttpModule is a station along the way.” Source: http://stackoverflow.com/questions/6449132/http-handler-vs-http-module
  • 5. Typical Uses HTTP Modules Security Statistics and logging Custom headers or footers HTTP Handlers RSS feeds Image server
  • 6. Custom HTTP Modules public class HelloWorldModule : IHttpModule { public void Init(HttpApplication application) { application.BeginRequest += (new EventHandler(this.Application_BeginRequest)); application.EndRequest += (new EventHandler(this.Application_EndRequest)); } private void Application_BeginRequest(Object source, EventArgs e) { HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; context.Response.Write("<h1><font color=red> HelloWorldModule: Beginning of Request </font></h1><hr>"); } private void Application_EndRequest(Object source, EventArgs e) { HttpApplication application = (HttpApplication)source; HttpContext context = application.Context; context.Response.Write("<hr><h1><font color=red> HelloWorldModule: End of Request</font></h1>"); } public void Dispose() { } } <configuration> <system.web> <httpModules> <add name="HelloWorldModule" type="HelloWorldModule"/> </httpModules> </system.web> </configuration> Source: http://msdn.microsoft.com/en-us/library/ms227673%28v=vs.85%29.aspx public interface IHttpModule { void Init(HttpApplication context); void Dispose(); }
  • 7. Custom HTTP Handlers using System.Web; public class HelloWorldHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpRequest Request = context.Request; HttpResponse Response = context.Response; Response.Write("<html>"); Response.Write("<body>"); Response.Write("<h1>Hello from a synchronous custom HTTP handler.</h1>"); Response.Write("</body>"); Response.Write("</html>"); } public bool IsReusable { get { return false; } } } public interface IHttpHandler { bool IsReusable { get; } void ProcessRequest(HttpContext context); } <configuration> <system.web> <httpHandlers> <add verb="*" path="*.sample" type="HelloWorldHandler"/> </httpHandlers> </system.web> </configuration> Source: http://msdn.microsoft.com/en-us/library/ms228090%28v=vs.100%29.aspx If you plan to write your own web framework this is good starting point.
  • 8. Existing HTTP Modules and HTTP Handlers HTTP Modules and HTTP Handlers are registered in .NET Framework’s Web.config: c:WindowsMicrosoft.NETFrameworkv4.0.30319Configweb.config Further info: http://programmer.lysik.pl/2013/08/asp-net-http-modules-and-http-handlers.html
  • 9. ASP.NET MVC Request Pipeline 1. Routing 2. Controller execution 3. Action execution 4. Result execution
  • 10. 1. Routing 2. Controller execution 3. Action execution 4. Result execution It all start with UrlRoutingModule.
  • 11. 1. Routing 2. Controller execution 3. Action execution 4. Result execution HTTP Handler HTTP Module 1 HTTP Module 2 UrlRoutingModule RouteTable.Routes MvcHandler
  • 12. 1. Routing 2. Controller execution 3. Action execution 4. Result execution MvcApplication (Global.asax) RouteTable.Routes (System.Web.Routing) System.Web.Mvc.RouteCollectionExtensions
  • 13. 1. Routing 2. Controller execution 3. Action execution 4. Result execution Url IRouteHandler Defaults Constraints DataTokens /Category/{action}/{id} PageRouteHandler … … … /{controller}/{action}/{id} MvcRouteHandler … … … … … … … … RouteTable.Routes (System.Web.Routing)RouteTable.Routes in fact contains: Classes that implement IRouteHandler are not HTTP handlers! But they should return one. System.Web.Mvc.MvcRouteHandler MvcHandler System.Web.Routing.PageRouteHandler Page or UrlAuthFailureHandler System.Web.WebPages.ApplicationParts.ResourceRouteHandler ResourceHandler System.ServiceModel.Activation.ServiceRouteHandler AspNetRouteServiceHttpHandler
  • 14. 1. Routing 2. Controller execution 3. Action execution 4. Result execution HTTP Handler HTTP Module 1 HTTP Module 2 UrlRoutingModule RouteTable.Routes MvcHandler
  • 15. 1. Routing 2. Controller execution 3. Action execution 4. Result execution UrlRoutingModule 1 2 3 4 RemapHandler tells IIS which HTTP handler we want to use. RouteTable.Routes
  • 16. 1. Routing 2. Controller execution 3. Action execution 4. Result execution 1 RouteTable.Routes (System.Web.Routing) RouteCollection public RouteData GetRouteData(HttpContextBase httpContext) { if (this.Count == 0) return (RouteData) null; . . . foreach (RouteBase routeBase in (Collection<RouteBase>) this) { RouteData routeData = routeBase.GetRouteData(httpContext); if (routeData != null) { return routeData; } } return (RouteData) null; } public override RouteData GetRouteData(HttpContextBase httpContext) { RouteValueDictionary values = this._parsedRoute.Match(httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo, this.Defaults); RouteData routeData = new RouteData((RouteBase) this, this.RouteHandler); if (!this.ProcessConstraints(httpContext, values, RouteDirection.IncomingRequest)) return (RouteData) null; . . . return routeData; } Route
  • 17. 1. Routing 2. Controller execution 3. Action execution 4. Result execution HTTP Handler HTTP Module 1 HTTP Module 2 UrlRoutingModule RouteTable.Routes MvcHandler 4
  • 18. 1. Routing 2. Controller execution 3. Action execution 4. Result execution MvcHandler Controller Builder 3. Call Execute on created Controller 2. Create Controller using ControllerFactory 1. Get ControllerFactory
  • 19. 1. Routing 2. Controller execution 3. Action execution 4. Result execution MvcHandler private void ProcessRequestInit(HttpContextBase httpContext, out IController controller, out IControllerFactory factory) { . . . string requiredString = this.RequestContext.RouteData.GetRequiredString("controller"); factory = this.ControllerBuilder.GetControllerFactory(); controller = factory.CreateController(this.RequestContext, requiredString); if (controller != null) return; . . . } 2 1 3
  • 20. 1. Routing 2. Controller execution 3. Action execution 4. Result execution factory = this.ControllerBuilder.GetControllerFactory(); controller = factory.CreateController(this.RequestContext, requiredString); 2 ControllerBuilder internal ControllerBuilder(IResolver<IControllerFactory> serviceResolver) { ControllerBuilder controllerBuilder = this; IResolver<IControllerFactory> resolver = serviceResolver; if (resolver == null) resolver = (IResolver<IControllerFactory>) new SingleServiceResolver<IControllerFactory>( (Func<IControllerFactory>) (() => this._factoryThunk()), (IControllerFactory) new DefaultControllerFactory() { ControllerBuilder = this }, "ControllerBuilder.GetControllerFactory"); controllerBuilder._serviceResolver = resolver; } public class CustomControllerFactory : IControllerFactory { public IController CreateController(RequestContext requestContext, string controllerName) { . . . } } public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { IControllerFactory factory = new CustomControllerFactory(); ControllerBuilder.Current.SetControllerFactory(factory); } } Custom Controller Factory MvcHandler
  • 21. 1. Routing 2. Controller execution 3. Action execution 4. Result execution Controller / ControllerBase Dependency Resolution 4. Call InvokeAction on action invoker. 3. Get action invoker. 2. Get action name from RouteData. 1. Call ExecuteCore 0. Execute being called by MvcHandler
  • 22. 1. Routing 2. Controller execution 3. Action execution 4. Result execution 3 ControllerBase Controller : ControllerBase protected override void ExecuteCore() { . . . string requiredString = this.RouteData.GetRequiredString("action"); this.ActionInvoker.InvokeAction(this.ControllerContext, requiredString); . . . }
  • 23. 1. Routing 2. Controller execution 3. Action execution 4. Result execution 3 Controller : ControllerBase protected virtual IActionInvoker CreateActionInvoker() { return (IActionInvoker) DependencyResolverExtensions.GetService<IAsyncActionInvoker>(this.Resolver) ?? DependencyResolverExtensions.GetService<IActionInvoker>(this.Resolver) ?? (IActionInvoker) new AsyncControllerActionInvoker(); } Possible methods of replacing default ActionInvoker: • Assign to ActionInvoker property. • Override CreateActionInvoker method. • Use dependency injection.
  • 24. 1. Routing 2. Controller execution 3. Action execution 4. Result execution 6. Invoke action result 5. Invoke action 4. Bind models. 3. Invoke authorization filters. 2. Find action using descriptor 1. Get controller descriptor (reflection). 0. InvokeAction being called by Controller.ExecuteCore ActionInvoker
  • 25. 1. Routing 2. Controller execution 3. Action execution 4. Result execution ControllerActionInvoker : IActionInvoker this.ActionInvoker.InvokeAction(this.ControllerContext, requiredString); 1 2 3 4 6 5
  • 26. 1. Routing 2. Controller execution 3. Action execution 4. Result execution 4 ControllerActionInvoker : IActionInvoker
  • 27. 1. Routing 2. Controller execution 3. Action execution 4. Result execution 6 ControllerActionInvoker : IActionInvoker
  • 28. 1. Routing 2. Controller execution 3. Action execution 4. Result execution ViewResultBase ViewResultBase ViewResult PartialViewResult
  • 29. 1. Routing 2. Controller execution 3. Action execution 4. Result execution ViewResult PartialViewResult
  • 30. 1. Routing 2. Controller execution 3. Action execution 4. Result execution JsonResult HttpStatusCodeResult