SlideShare a Scribd company logo
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?
Ad

Recommended

PPTX
"Нягтлан бодох бүртгэлийн үндэс" Хичээл - 6
E-Gazarchin Online University
 
PPTX
Lec 02 - copy (2)
Enhmandah Hemeelee
 
PPTX
бүлэг 1
oyunsuren84
 
DOCX
Aula eletroanalitica 1 marco
Marco Bumba
 
PDF
[오픈소스컨설팅]Session 4. dev ops 구성 사례와 전망
Open Source Consulting
 
DOCX
лекц 4
oyunsuren84
 
PPTX
Saf maddələr və qarışıqlar.pptx
Modern Educator - Vali Aliyev
 
PPT
IFRS-2021 presentation.ppt
anujinmunkhbat3
 
PDF
analise instrumental
Adrianne Mendonça
 
PPTX
үйлдвэрлэлийн үйл ажиллагаанд нөлөөлөх орчин үеийн асуудлууд
Delgermaa Battulga
 
PDF
Олон улсын санхүүгийн зах зээлийн арилжааны техник шинжилгээ-1 http:/...
Adilbishiin Gelegjamts
 
PDF
Jakarta EEとMicroprofileの上手な付き合い方と使い方 - JakartaOne Livestream Japan 2020
Hirofumi Iwasaki
 
PPT
Ias 20
unenbat4411
 
PPTX
Metallic Bond
ROBI Axiata Company Limited
 
PPTX
Нягтлан бодох бүртгэлийн үндэс хичээл 2 Шинэ Иргэншил Дээд Сургууль
Chuluun Zulaa
 
PPTX
B sc_I_General chemistry U-II Ionic equilibria in aqueous solution
Rai University
 
DOCX
компаний үйл ажиллагаа нээлттэй ил тод байхын ач холбогдол
Delgermaa Battulga
 
PPTX
лекц 5,6
uugii4411
 
PDF
HP NonStop applications: Modernization from the Ground-up and the User-in
Thomas Burg
 
PDF
audit test
ssuser95389c
 
PPT
Lekts 7 uil ajillagaanii shinjilgee
Byambadrj Myagmar
 
PPTX
шинэ татвар төлөгчид
Tengis Munkhjargal
 
PPT
Fundamentals of accounting
Baterdene Batchuluun
 
PPTX
Lecture 10
Odko Ts
 
PPTX
бүлэг 2
oyunsuren84
 
PPTX
Et 2016.12.26
GeoMedeelel
 
PPTX
OCI Logging 概要
オラクルエンジニア通信
 
PDF
ASP.NET Internals
GoSharp
 
PPTX
How to get full power from WebApi
Raffaele Rialdi
 

More Related Content

What's hot (20)

PDF
analise instrumental
Adrianne Mendonça
 
PPTX
үйлдвэрлэлийн үйл ажиллагаанд нөлөөлөх орчин үеийн асуудлууд
Delgermaa Battulga
 
PDF
Олон улсын санхүүгийн зах зээлийн арилжааны техник шинжилгээ-1 http:/...
Adilbishiin Gelegjamts
 
PDF
Jakarta EEとMicroprofileの上手な付き合い方と使い方 - JakartaOne Livestream Japan 2020
Hirofumi Iwasaki
 
PPT
Ias 20
unenbat4411
 
PPTX
Metallic Bond
ROBI Axiata Company Limited
 
PPTX
Нягтлан бодох бүртгэлийн үндэс хичээл 2 Шинэ Иргэншил Дээд Сургууль
Chuluun Zulaa
 
PPTX
B sc_I_General chemistry U-II Ionic equilibria in aqueous solution
Rai University
 
DOCX
компаний үйл ажиллагаа нээлттэй ил тод байхын ач холбогдол
Delgermaa Battulga
 
PPTX
лекц 5,6
uugii4411
 
PDF
HP NonStop applications: Modernization from the Ground-up and the User-in
Thomas Burg
 
PDF
audit test
ssuser95389c
 
PPT
Lekts 7 uil ajillagaanii shinjilgee
Byambadrj Myagmar
 
PPTX
шинэ татвар төлөгчид
Tengis Munkhjargal
 
PPT
Fundamentals of accounting
Baterdene Batchuluun
 
PPTX
Lecture 10
Odko Ts
 
PPTX
бүлэг 2
oyunsuren84
 
PPTX
Et 2016.12.26
GeoMedeelel
 
PPTX
OCI Logging 概要
オラクルエンジニア通信
 
analise instrumental
Adrianne Mendonça
 
үйлдвэрлэлийн үйл ажиллагаанд нөлөөлөх орчин үеийн асуудлууд
Delgermaa Battulga
 
Олон улсын санхүүгийн зах зээлийн арилжааны техник шинжилгээ-1 http:/...
Adilbishiin Gelegjamts
 
Jakarta EEとMicroprofileの上手な付き合い方と使い方 - JakartaOne Livestream Japan 2020
Hirofumi Iwasaki
 
Ias 20
unenbat4411
 
Нягтлан бодох бүртгэлийн үндэс хичээл 2 Шинэ Иргэншил Дээд Сургууль
Chuluun Zulaa
 
B sc_I_General chemistry U-II Ionic equilibria in aqueous solution
Rai University
 
компаний үйл ажиллагаа нээлттэй ил тод байхын ач холбогдол
Delgermaa Battulga
 
лекц 5,6
uugii4411
 
HP NonStop applications: Modernization from the Ground-up and the User-in
Thomas Burg
 
audit test
ssuser95389c
 
Lekts 7 uil ajillagaanii shinjilgee
Byambadrj Myagmar
 
шинэ татвар төлөгчид
Tengis Munkhjargal
 
Fundamentals of accounting
Baterdene Batchuluun
 
Lecture 10
Odko Ts
 
бүлэг 2
oyunsuren84
 
Et 2016.12.26
GeoMedeelel
 

Similar to ASP.NET MVC 4 Request Pipeline Internals (20)

PDF
ASP.NET Internals
GoSharp
 
PPTX
How to get full power from WebApi
Raffaele Rialdi
 
PPTX
Http pipeline
vrluckyin
 
PPTX
Http pipeline
icubesystem
 
PPTX
Skillwise - Advanced web application development
Skillwise Group
 
PDF
Asp.Net MVC Framework Design Pattern
maddinapudi
 
PPTX
Understanding ASP.NET Under The Cover - Miguel A. Castro
Mohammad Tayseer
 
PPTX
ASP.NET lecture 8
Julie Iskander
 
PDF
ASP.NET MVC Internals
Vitaly Baum
 
PDF
ASP.NET MVC 2.0
Buu Nguyen
 
PPTX
Web api
udaiappa
 
PPTX
Middleware
Eliana Caraballo
 
PPTX
CodeCamp Iasi 10 March 2012 - Gabriel Enea - ASP.NET Web API
Codecamp Romania
 
PPTX
Asp.net web api extensibility
Eyal Vardi
 
PPTX
The ASP.NET Web API for Beginners
Kevin Hazzard
 
PPTX
The Functional Web
Ryan Riley
 
PPTX
ASP.NET - Building Web Application..in the right way!
Commit Software Sh.p.k.
 
PPTX
ASP.NET - Building Web Application..in the right way!
Fioriela Bego
 
PPTX
Asp.NET Handlers and Modules
py_sunil
 
PPTX
Hanselman lipton asp_connections_ams304_mvc
denemedeniz
 
ASP.NET Internals
GoSharp
 
How to get full power from WebApi
Raffaele Rialdi
 
Http pipeline
vrluckyin
 
Http pipeline
icubesystem
 
Skillwise - Advanced web application development
Skillwise Group
 
Asp.Net MVC Framework Design Pattern
maddinapudi
 
Understanding ASP.NET Under The Cover - Miguel A. Castro
Mohammad Tayseer
 
ASP.NET lecture 8
Julie Iskander
 
ASP.NET MVC Internals
Vitaly Baum
 
ASP.NET MVC 2.0
Buu Nguyen
 
Web api
udaiappa
 
Middleware
Eliana Caraballo
 
CodeCamp Iasi 10 March 2012 - Gabriel Enea - ASP.NET Web API
Codecamp Romania
 
Asp.net web api extensibility
Eyal Vardi
 
The ASP.NET Web API for Beginners
Kevin Hazzard
 
The Functional Web
Ryan Riley
 
ASP.NET - Building Web Application..in the right way!
Commit Software Sh.p.k.
 
ASP.NET - Building Web Application..in the right way!
Fioriela Bego
 
Asp.NET Handlers and Modules
py_sunil
 
Hanselman lipton asp_connections_ams304_mvc
denemedeniz
 
Ad

Recently uploaded (20)

PDF
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
PPTX
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
PDF
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
PPTX
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
PDF
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
PDF
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
PDF
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
PDF
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PPTX
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
PDF
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
PDF
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
PPTX
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
PDF
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
PDF
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
PDF
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
PPTX
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
PDF
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Ad

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