SlideShare a Scribd company logo
Vitaly Baum @butaji
ASP.NET MVC Internals
> whoami
Vitaly Baum
Product Manager @ bright box
vitaly.baum@gmail.com
http://twitter.com/butaji
BACKGROUND
▪Web Application
▪MVC
▪What and How
▪Controller
▪How do I write Controllers?
▪How do requests come to Controller?
▪View
▪How does ViewEngine render views?
▪Why do I need to change ViewEngine?
AGENDA
QUESTIONS
• Non-IIS
• Azure in production
• NoSQL
• NGINX
OK. MVC
MVC
• Front Controller
An object that handles all requests
• Page Controller
An object that handles a request for a specific page
or action on a Web site
HTTP
HTTP
1. Request
2. Environment
3. Response
IIS
• System.Web.dll
• IHttpHandler (extensions)
• IHttpModule (HttpApplication events)
using System;
using System.Web;
public class LoggingHttpModule : IHttpModule
{
public void Dispose() {}
public void Init(HttpApplication context)
{
context.BeginRequest += BeginRequest;
}
void BeginRequest(object sender, EventArgs e)
{
Logger.Instance.Log("Hi there!");
}
}
public class RequestHandler : IHttpHandler
{
public RequestHandler() { }
public bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write("{ id : 1 }");
}
}
ASP.NET MVC?
• Were implemented on HttpHandlers
• https://servicestack.net/features
• http://www.castleproject.org/projects/monorail/
• http://mvc.fubu-project.org
IIS + ASP.NET
• Highly coupled
• Hard to manage (ain’t my job)
• New features only with OS updates
a. Web Server
b. Middleware
c. Application
SERVER INTEROP
• authentication
• cookies
• authorization
• output caching
• localisation
• request servicing (app)
MIDDLEWARE
SERVER INTEROP
• Rack (ruby)
• WSGI (Python)
• Node.js
• OWIN (.NET)
require	
  'rack'	
  
	
  	
  
app	
  =	
  Proc.new	
  do	
  |env|	
  #	
  ENV	
  HASH	
  
	
  	
  	
  	
  [	
  
'200',	
  #	
  HTTP	
  CODE	
  
{'Content-­‐Type'	
  =>	
  'text/html'},	
  	
  
['A	
  barebones	
  rack	
  app.’]	
  #	
  BODY	
  
	
  	
  ]	
  
end	
  
	
  	
  
Rack::Handler::WEBrick.run	
  app
MIDDLEWARE
var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200,
{'Content-Type': 'text/plain'});
res.end('Hello Worldn');
})
server.listen(1337, '127.0.0.1');
MIDDLEWARE
var	
  express	
  =	
  require('express')	
  
var	
  app	
  =	
  express()	
  
app.use(function	
  (req,	
  res,	
  next)	
  {	
  
	
  	
  console.log('Time:',	
  Date.now());	
  
	
  	
  next();	
  
});	
  
MIDDLEWARE
//OWIN Implementation
using AppFunc = Func<
IDictionary<string, object>,
Task
>;
MIDDLEWARE
OWIN
public	
  class	
  Startup	
  
{	
  
public	
  void	
  Configuration(IAppBuilder	
  app)	
  
{	
  
app.Run(context	
  =>	
  {	
  
return	
  context	
  
.Response.WriteAsync("Hi	
  OWIN/Katana");	
  
});	
  
}	
  
}
ASP.NET MVC
ASP.NET MVC LIFECYCLE
Routing
UrlRoutingModule -> IRouteHandler ->
IHttpHandler
Controller
Execute -> Filters -> Model Binding -> Action
Action
Your Code
Result
Views -> TypeFormater
ROUTE HANDLER
public	
  class	
  MyRouteHandler	
  :	
  IRouteHandler	
  
{	
  
	
  	
  	
  public	
  IHttpHandler	
  GetHttpHandler(	
  
RequestContext	
  requestContext)	
  
	
  	
  	
  {	
  
	
  	
  	
  	
  	
  	
  	
  var	
  handler	
  =	
  new	
  MyMVCHandler();	
  
	
  	
  	
  	
  	
  	
  	
  handler.RequestContext	
  =	
  requestContext;	
  
	
  	
  	
  	
  	
  	
  	
  return	
  handler;	
  
	
  	
  	
  	
  }	
  
}
ROUTE HANDLER
• In case of dynamic routes
• CMS
• Blog with custom Slugs
MVC HANDLER
public	
  class	
  MyMVCHandler	
  :	
  MvcHandler

{

	
  	
  	
  	
  protected	
  override	
  void	
  ProcessRequest(IHttpContext	
  
httpContext)

	
  	
  	
  	
  {

var	
  controllerName	
  =	
  
GetRequiredString(this.RequestContext.RouteData,	
  "controller");	
  
	
  	
  	
  	
  	
  	
  	
  var	
  controller	
  =	
  CreateController(controllerName);

	
  	
  	
  	
  	
  	
  	
  var	
  controllerContext	
  =	
  new	
  
ControllerContext(base.RequestContext,	
  controller);	
  
	
  	
  	
  	
  	
  	
  	
  controller.Execute(controllerContext);

	
  	
  	
  	
  }	
  
	
  	
  	
  	
  private	
  IController	
  CreateController(string	
  controllerName)

	
  	
  	
  	
  {

	
  	
  	
  	
  	
  	
  return	
  _controllerFactory.Create(controllerName);

	
  	
  	
  	
  }

}
DEPENDENCY MGMT
public	
  class	
  CustomControllerFactory	
  :	
  IControllerFactory	
  
{	
  
	
  	
  public	
  IController	
  CreateController(RequestContext	
  
requestContext,	
  string	
  name)	
  
	
  	
  {	
  
	
  	
  	
  	
  	
  	
  return	
  _serviceLocator.Resolve<IController>(name);	
  
	
  }	
  
}	
  
DEPENDENCY MGMT
//ASP.NET	
  vNext	
  has	
  new	
  way	
  to	
  inject	
  dependencies	
  
public	
  class	
  Startup	
  
{	
  
	
  	
  public	
  void	
  Configure(IBuilder	
  app)	
  
	
  	
  {	
  
	
  	
  	
  	
  var	
  services	
  =	
  new	
  ServiceCollection();	
  
	
  	
  	
  	
  services.AddTransient<IMessageGenerator,	
  
HelloMessageGenerator>();	
  
	
  	
  	
  	
  app.UseMiddleware(typeof(ContainerMiddleware));	
  
	
  	
  }	
  
}	
  
OK. CTRL
CONTROLLER
FAT VS SKINNY
CONTROLLER
[HttpPost,	
  ActionName("Delete")]	
  
public	
  async	
  Task<ActionResult>	
  DeleteConfirmed(int	
  id)	
  
{	
  
var	
  album	
  =	
  await	
  _storeContext.Albums.FindAsync(id);	
  
if	
  (album	
  ==	
  null)	
  
{	
  
return	
  HttpNotFound();	
  
}	
  
_storeContext.Albums.Remove(album);	
  
await	
  _storeContext.SaveChangesAsync();	
  
return	
  RedirectToAction("Index");	
  
}	
  
CONTROLLER
[HttpPost,	
  ActionName("Delete")]	
  
public	
  async	
  Task<ActionResult>	
  DeleteConfirmed(int	
  id)	
  
{	
  
var	
  removed	
  =	
  await	
  _albumService.Remove(id);	
  
return	
  Status.NotFound	
  ==	
  removed.Status	
  
?	
  HttpNotFound()	
  
:	
  RedirectToAction(“Index");	
  
}	
  
CONTROLLER
//vNext	
  can	
  host	
  POCOs	
  controllers	
  
public	
  List<Data>	
  GetData()	
  
{	
  
return	
  null;	
  //will	
  return	
  204	
  (NoContent)	
  
}
def {action_name}( {params} )
app_res = {domain_service}.{call}( {params} )
return app_res
end
OK. VIEW
SEO OF SPA
SEO OF SPA
MIDDLEWARE
Middleware
Application
GET /
User-Agent: Chrome
GET /
User-Agent: Google
JSON
Middleware
Application
GET /
User-Agent: Google
GET /
User-Agent: Chrome
HTML
SEO OF SPA
SHARED TEMPLATES
SHARED TEMPLATES
Server Client
Template
}http://mustache.github.io
{{#repo}}
<b>{{name}}</b>
{{/repo}}
{
"repo": [
{ "name": "resque" },
{ "name": "hub" },
{ "name": "rip" }
]
}
<b>resque</b>
<b>hub</b>
<b>rip</b>+ =
YET ANOTHER TEMPLATE
VIEW ENGINE
public	
  interface	
  IViewEngine	
  	
  
{	
  
	
  	
  	
  ViewEngineResult	
  FindPartialView(ControllerContext	
  ctx,	
  string	
  
name,	
  bool	
  useCache);	
  
	
  	
  	
  ViewEngineResult	
  FindView(ControllerContext	
  ctx,	
  string	
  viewName,	
  
string	
  masterName,	
  bool	
  useCache);	
  
	
  	
  	
  void	
  ReleaseView(ControllerContext	
  ctx,	
  IView	
  view);	
  
}	
  
public	
  interface	
  IView	
  	
  
{	
  
	
  	
  void	
  Render(ViewContext	
  ctx,	
  TextWriter	
  writer);	
  
}
http://buildstarted.com/2013/12/16/javascript-view-engine-for-aspnet/
VIEW ENGINE
services.AddMvc().Configure<MvcOptions>(	
  
options	
  =>	
  
{	
  
options.ViewEngines.Add(	
  
new	
  MyCustomerViewEngine	
  ());	
  
});
COVERED TOPICS
▪Web Application
▪MVC
▪What and How
▪Controller
▪How do I write Controllers?
▪How do requests come to Controller?
▪View
▪How does ViewEngine render views?
▪Why do I need to change ViewEngine?
THANK
YOU
Vitaly Baum
@butaji

More Related Content

PDF
Introduction to ReactJS
PDF
ASP.NET Internals
PDF
Switch to React.js from AngularJS developer
PPTX
React, Flux and a little bit of Redux
PDF
Angular2 & ngrx/store: Game of States
PDF
Designing applications with Redux
PDF
Modern Web Developement
PDF
Creating a WYSIWYG Editor with React
Introduction to ReactJS
ASP.NET Internals
Switch to React.js from AngularJS developer
React, Flux and a little bit of Redux
Angular2 & ngrx/store: Game of States
Designing applications with Redux
Modern Web Developement
Creating a WYSIWYG Editor with React

What's hot (20)

PPTX
Academy PRO: React JS. Redux & Tooling
PDF
React 101
PDF
How Angular2 Can Improve Your AngularJS Apps Today!
PDF
React state management with Redux and MobX
PDF
React state managmenet with Redux
PPTX
Redux training
PDF
Redux js
PPTX
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
PDF
Redux vs Alt
PDF
Workshop 14: AngularJS Parte III
PDF
Angular js vs. Facebook react
PDF
Introduction to React & Redux
PPTX
Getting started with ReactJS
PDF
Advanced redux
PPTX
Better web apps with React and Redux
PDF
Using redux
PPTX
React / Redux Architectures
PDF
JS Chicago Meetup 2/23/16 - Redux & Routes
PPTX
React with Redux
PPTX
Academy PRO: React JS. Redux & Tooling
React 101
How Angular2 Can Improve Your AngularJS Apps Today!
React state management with Redux and MobX
React state managmenet with Redux
Redux training
Redux js
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
Redux vs Alt
Workshop 14: AngularJS Parte III
Angular js vs. Facebook react
Introduction to React & Redux
Getting started with ReactJS
Advanced redux
Better web apps with React and Redux
Using redux
React / Redux Architectures
JS Chicago Meetup 2/23/16 - Redux & Routes
React with Redux
Ad

Similar to ASP.NET MVC Internals (20)

PDF
Asp.Net MVC Framework Design Pattern
PPTX
Hanselman lipton asp_connections_ams304_mvc
PPTX
Hands on with ASP.NET MVC
PPTX
MVC 6 - the new unified Web programming model
PPTX
PPTX
ASP.NET - Building Web Application..in the right way!
PPTX
ASP.NET - Building Web Application..in the right way!
PPTX
Asp.net mvc 6 with sql server 2014
PPTX
Asp.net mvc
PPT
CTTDNUG ASP.NET MVC
PPTX
Ria 03 - Hello ASP.NET MVC
PPTX
Introduction to ASP.Net MVC
PDF
ASP.NET Core Web API documentation web application
PPTX
How to get full power from WebApi
PPTX
Deep Dive: MVC Controller Architecture
PPTX
Developing ASP.NET Applications Using the Model View Controller Pattern
PDF
ASP.NET MVC - Whats The Big Deal
PPT
ASP .net MVC
PDF
Programming ASP NET MVC 4 Developing Real World Web Applications with ASP NET...
PPTX
What's new in asp.net mvc 4
Asp.Net MVC Framework Design Pattern
Hanselman lipton asp_connections_ams304_mvc
Hands on with ASP.NET MVC
MVC 6 - the new unified Web programming model
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
Asp.net mvc 6 with sql server 2014
Asp.net mvc
CTTDNUG ASP.NET MVC
Ria 03 - Hello ASP.NET MVC
Introduction to ASP.Net MVC
ASP.NET Core Web API documentation web application
How to get full power from WebApi
Deep Dive: MVC Controller Architecture
Developing ASP.NET Applications Using the Model View Controller Pattern
ASP.NET MVC - Whats The Big Deal
ASP .net MVC
Programming ASP NET MVC 4 Developing Real World Web Applications with ASP NET...
What's new in asp.net mvc 4
Ad

Recently uploaded (20)

PDF
Transforming Manufacturing operations through Intelligent Integrations
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Modernizing your data center with Dell and AMD
PPTX
Big Data Technologies - Introduction.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Empathic Computing: Creating Shared Understanding
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Transforming Manufacturing operations through Intelligent Integrations
NewMind AI Monthly Chronicles - July 2025
AI And Its Effect On The Evolving IT Sector In Australia - Elevate
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
20250228 LYD VKU AI Blended-Learning.pptx
CIFDAQ's Market Insight: SEC Turns Pro Crypto
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
Review of recent advances in non-invasive hemoglobin estimation
Modernizing your data center with Dell and AMD
Big Data Technologies - Introduction.pptx
NewMind AI Weekly Chronicles - August'25 Week I
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Sensors and Actuators in IoT Systems using pdf
Empathic Computing: Creating Shared Understanding
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
GamePlan Trading System Review: Professional Trader's Honest Take
Diabetes mellitus diagnosis method based random forest with bat algorithm

ASP.NET MVC Internals

  • 2. > whoami Vitaly Baum Product Manager @ bright box [email protected] http://twitter.com/butaji BACKGROUND
  • 3. ▪Web Application ▪MVC ▪What and How ▪Controller ▪How do I write Controllers? ▪How do requests come to Controller? ▪View ▪How does ViewEngine render views? ▪Why do I need to change ViewEngine? AGENDA
  • 4. QUESTIONS • Non-IIS • Azure in production • NoSQL • NGINX
  • 6. MVC • Front Controller An object that handles all requests • Page Controller An object that handles a request for a specific page or action on a Web site
  • 9. IIS • System.Web.dll • IHttpHandler (extensions) • IHttpModule (HttpApplication events)
  • 10. using System; using System.Web; public class LoggingHttpModule : IHttpModule { public void Dispose() {} public void Init(HttpApplication context) { context.BeginRequest += BeginRequest; } void BeginRequest(object sender, EventArgs e) { Logger.Instance.Log("Hi there!"); } }
  • 11. public class RequestHandler : IHttpHandler { public RequestHandler() { } public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; context.Response.Write("{ id : 1 }"); } }
  • 12. ASP.NET MVC? • Were implemented on HttpHandlers • https://servicestack.net/features • http://www.castleproject.org/projects/monorail/ • http://mvc.fubu-project.org
  • 13. IIS + ASP.NET • Highly coupled • Hard to manage (ain’t my job) • New features only with OS updates
  • 14. a. Web Server b. Middleware c. Application SERVER INTEROP
  • 15. • authentication • cookies • authorization • output caching • localisation • request servicing (app) MIDDLEWARE
  • 16. SERVER INTEROP • Rack (ruby) • WSGI (Python) • Node.js • OWIN (.NET)
  • 17. require  'rack'       app  =  Proc.new  do  |env|  #  ENV  HASH          [   '200',  #  HTTP  CODE   {'Content-­‐Type'  =>  'text/html'},     ['A  barebones  rack  app.’]  #  BODY      ]   end       Rack::Handler::WEBrick.run  app MIDDLEWARE
  • 18. var http = require('http'); var server = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }) server.listen(1337, '127.0.0.1'); MIDDLEWARE
  • 19. var  express  =  require('express')   var  app  =  express()   app.use(function  (req,  res,  next)  {      console.log('Time:',  Date.now());      next();   });   MIDDLEWARE
  • 20. //OWIN Implementation using AppFunc = Func< IDictionary<string, object>, Task >; MIDDLEWARE
  • 21. OWIN public  class  Startup   {   public  void  Configuration(IAppBuilder  app)   {   app.Run(context  =>  {   return  context   .Response.WriteAsync("Hi  OWIN/Katana");   });   }   }
  • 23. ASP.NET MVC LIFECYCLE Routing UrlRoutingModule -> IRouteHandler -> IHttpHandler Controller Execute -> Filters -> Model Binding -> Action Action Your Code Result Views -> TypeFormater
  • 24. ROUTE HANDLER public  class  MyRouteHandler  :  IRouteHandler   {        public  IHttpHandler  GetHttpHandler(   RequestContext  requestContext)        {                var  handler  =  new  MyMVCHandler();                handler.RequestContext  =  requestContext;                return  handler;          }   }
  • 25. ROUTE HANDLER • In case of dynamic routes • CMS • Blog with custom Slugs
  • 26. MVC HANDLER public  class  MyMVCHandler  :  MvcHandler
 {
        protected  override  void  ProcessRequest(IHttpContext   httpContext)
        {
 var  controllerName  =   GetRequiredString(this.RequestContext.RouteData,  "controller");                var  controller  =  CreateController(controllerName);
              var  controllerContext  =  new   ControllerContext(base.RequestContext,  controller);                controller.Execute(controllerContext);
        }          private  IController  CreateController(string  controllerName)
        {
            return  _controllerFactory.Create(controllerName);
        }
 }
  • 27. DEPENDENCY MGMT public  class  CustomControllerFactory  :  IControllerFactory   {      public  IController  CreateController(RequestContext   requestContext,  string  name)      {              return  _serviceLocator.Resolve<IController>(name);    }   }  
  • 28. DEPENDENCY MGMT //ASP.NET  vNext  has  new  way  to  inject  dependencies   public  class  Startup   {      public  void  Configure(IBuilder  app)      {          var  services  =  new  ServiceCollection();          services.AddTransient<IMessageGenerator,   HelloMessageGenerator>();          app.UseMiddleware(typeof(ContainerMiddleware));      }   }  
  • 31. CONTROLLER [HttpPost,  ActionName("Delete")]   public  async  Task<ActionResult>  DeleteConfirmed(int  id)   {   var  album  =  await  _storeContext.Albums.FindAsync(id);   if  (album  ==  null)   {   return  HttpNotFound();   }   _storeContext.Albums.Remove(album);   await  _storeContext.SaveChangesAsync();   return  RedirectToAction("Index");   }  
  • 32. CONTROLLER [HttpPost,  ActionName("Delete")]   public  async  Task<ActionResult>  DeleteConfirmed(int  id)   {   var  removed  =  await  _albumService.Remove(id);   return  Status.NotFound  ==  removed.Status   ?  HttpNotFound()   :  RedirectToAction(“Index");   }  
  • 33. CONTROLLER //vNext  can  host  POCOs  controllers   public  List<Data>  GetData()   {   return  null;  //will  return  204  (NoContent)   }
  • 34. def {action_name}( {params} ) app_res = {domain_service}.{call}( {params} ) return app_res end
  • 40. SEO OF SPA SHARED TEMPLATES
  • 43. {{#repo}} <b>{{name}}</b> {{/repo}} { "repo": [ { "name": "resque" }, { "name": "hub" }, { "name": "rip" } ] } <b>resque</b> <b>hub</b> <b>rip</b>+ = YET ANOTHER TEMPLATE
  • 44. VIEW ENGINE public  interface  IViewEngine     {        ViewEngineResult  FindPartialView(ControllerContext  ctx,  string   name,  bool  useCache);        ViewEngineResult  FindView(ControllerContext  ctx,  string  viewName,   string  masterName,  bool  useCache);        void  ReleaseView(ControllerContext  ctx,  IView  view);   }   public  interface  IView     {      void  Render(ViewContext  ctx,  TextWriter  writer);   } http://buildstarted.com/2013/12/16/javascript-view-engine-for-aspnet/
  • 45. VIEW ENGINE services.AddMvc().Configure<MvcOptions>(   options  =>   {   options.ViewEngines.Add(   new  MyCustomerViewEngine  ());   });
  • 46. COVERED TOPICS ▪Web Application ▪MVC ▪What and How ▪Controller ▪How do I write Controllers? ▪How do requests come to Controller? ▪View ▪How does ViewEngine render views? ▪Why do I need to change ViewEngine?