SlideShare uma empresa Scribd logo
1 de 70
UNDERSTANDING  ASP.NETUNDER THE COVERS Miguel A. Castro miguel.castro@idesign.net
Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
ineta Miguel A. Castro ,[object Object]
 Microsoft MVP
 ASP Insider
 Member of the INETA Speakers Bureau
 Conference Speaker
 Creator of CodeBreeze
 In IT business since 1986,[object Object]
Classic ASP Interpreted language Included embedded scripting code mixed into HTML Limited to VBScript Ran in the same process as IIS Inherently not scalable (needed MTS) End of line
Classic ASP End of line
Walking Upright Designed by Scott Guthrie & Mark Anders Early iteration of ASP.NET Originally known as XSP Not .NET-related – Java based ! Became ASP+ with the design of the CLR Rewritten in C# Renamed when .NET branding introduced End of line
What is ASP.NET A framework for developing and delivering information & applications on the web. Known primarily as a page framework. A complete Request/Response management system. Can handle and respond to all sorts of requests on the Internet (or an Intranet). Not a language ! End of line
Characteristics of ASP.NET Runs under its own worker process. No longer tied to IIS. Code execution managed by CLR. Code-Behind model allows code separation. Includes state handling facilities. Provides caching functionality. End of line
Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
Commonly Used Terms Request An HTTP query initiated by a client to a server for the purpose of performing some action. Response A stream of information sent back to a client from the HTTP server that processed the client’s request. ASP.NET Pipeline A series of extensible functionality points which continue the process of a request in order to eventually obtain a response. End of line
Commonly Used Terms Page Lifecycle Another series of functionality points that form the process of converting an ASPX page to HTML output. The entire page lifecycle occurs between two pipeline points. Control Model The heart of how ASP.NET builds HTML from compiled classes that represent visual components. End of line
Commonly Used Terms HTTP Handlers Classes that are the target of HTTP requests. Assigned by file extension & verb. Map to ISAPI Extensions HTTP Modules Classes that inject mode into the pipeline. Map to ISAPI Filters MVC An design pattern that separates the output design from the information that builds it. End of line
Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
What Everyone Sees Desktop Browser Web Server (IIS) http://www.microsoft.com/default.aspx Rendered HTML Now the long version… End of line
Getting it to .NET (the low level stuff) Web Server (IIS) Web Server (IIS) Kernel Mode Driver:Http API used by IIS http.sys Worker Process(w3wp.exe) – (one per app pool) Worker Process started (one per pool) and if needed, AppDomain is created. aspnet_isapi.dll AppDomain (one per site/VD) Attached to the extension of the request. Unmanaged DLL that loads the CLR and routes requests to the managed runtime classes via COM-compliant interfaces.  ISAPIRuntime(ProcessRequest method) HttpRuntime.ProcessRequest Request sent to the ASP.NET runtime for processing. End of line
ASP.NET Takes Over HttpRuntime.ProcessRequest  Accessible from now until the end of the request processing.  Accessible through HttpContext.Current HttpContext created. This serves as an entry point into the request, response, and other accessible variables. Each AppDomain manages multiple instances so they do not conflict with each other (different users or same user with more than one request). An HttpApplication instance is created. HttpApplication This is where it starts to mean something to you, the developer. Init method starts pipeline processing. End of line
Entering the Pipeline Pipeline kicked off in the Init method. HttpApplication BeginRequest Performs event processing. AuthenticateRequest / Post AuthorizeRequest / Post Checks hooks from Global.asax class. ResolveRequestCache / Post Checks hooks from external HTTP Modules. MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post ReleaseRequestState / Post UpdateRequestCache / Post LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
Entering the Pipeline HttpApplication BeginRequest AuthenticateRequest / Post AuthorizeRequest / Post ResolveRequestCache / Post MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post ReleaseRequestState / Post UpdateRequestCache / Post LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
Pipeline Events of Interest HttpApplication Provide URL-Rewriting functionality. BeginRequest AuthenticateRequest / Post Repopulate HttpContext.Current.User with stored principal. Page authentication occurs here. AuthorizeRequest / Post ResolveRequestCache / Post MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post Determine whether to use cached response. ReleaseRequestState / Post UpdateRequestCache / Post Any event can be hooked in Global.asax or in an HTTP Module. LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
HTTP Modules Classes that implement IHttpModule. MyModule : IHttpModule Delegate-based Properties in HttpApplication instance can be wired up. Method functionality equivalent to hooking event in Global.asax Event hooks in modules checked during pipeline processing. End of line
AuthenticateRequest WindowsAuthenticationModule FormsAuthenticationModule UrlAuthenticationModule FileAuthorizationModule ServiceModel SessionStateModule OutputCacheModule AuthenticateRequest EndRequest AuthorizeRequest AuthorizeRequest PostAuthenticateRequest AcquireRequestState AcquireRequestState ReleaseRequestState EndRequest ASP.NET HTTP Modules of Interest End of line
Module Installation Any level in the Config chain You do know what the Config chain is, right? End of line
The Process Continues HttpApplication Just before this event: Proper HTTP Handler located based on request’s extension. BeginRequest AuthenticateRequest / Post Handlers provide necessary processing in order to create a response. AuthorizeRequest / Post ResolveRequestCache / Post MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post ReleaseRequestState / Post UpdateRequestCache / Post LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
HTTP Handlers Classes that implement IHttpHandler. Determines if the handler instance can be reused by another request. MyHandler : IHttpHandler Functionality assigned to this particular handler. Remember the HttpContext contains all accessible variables, including Response. End of line
HTTP Handler Factories Can also implement IHttpHandlerFactory. Allows the instantiation of any handler based on specific conditioning scenarios. MyHandlerFactory : IHttpHandlerFactory End of line
Characteristics of an HTTP Handler Access to current HttpContext. Request is in there (as is the Response) ! Handlers are wired to extensions (aspx, etc.). Every handler is responsible for what the response is going to be for a request. ASPX requests expect an HTML response. Config requests expect a “forbidden” response. End of line
Handler Execution HttpApplication BeginRequest AuthenticateRequest / Post AuthorizeRequest / Post The determined handler is processed between the PreRequestHandlerExecute and PostRequestHandlerExecute. ResolveRequestCache / Post MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post ReleaseRequestState / Post UpdateRequestCache / Post LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
Handler Installation Handler factory that returns and executes the handler that will convert an ASPX page to HTML output. Any level in the Config chain End of line
The PageHandlerFactory Class Implements IHttpHandlerFactory. GetHandler method returns an IHttpHandler in the form of System.Web.UI.Page-derived class hierarchy. Page class implements IHttpHandler. Page class inherits from Control. Control contains events/methods for the “Page Event Lifecycle”. PageHandlerFactory creates a class structure out of your request. End of line
Page Class Structure Follows the structure of an ASP.NET Server Control. Referred to as Page-Gen Class. Created by the PageHandlerFactory class Virtual class created from ASPX page. Controls created based on ASPX content. inherits Partial class with control declarations (class name same as code-behind). partials with Code-behind class is other side of partial class. This is why you can tap into events from your code-behind. inherits ProcessRequest method calls lifecycle events in Control. System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
Page Class Structure Created by the PageHandlerFactory class Virtual class created from ASPX page. inherits Partial class with control declarations (class name same as code-behind). partials with Code-behind class is other side of partial class. inherits System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
Virtual Class Created from ASPX content Determines language to be used to generate page-gen class. Specifies the partial class to serve as the code-behind. Optional: Name of the code-file for Visual Studio. End of line
Virtual Class Created from ASPX content LiteralControl Converted to instances of System.Web.UI.LiteralControl that are added to the control tree of this class. Remember, this class will ultimately inherit from System.Web.UI.Control LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
Virtual Class Created from ASPX content LiteralControl LiteralControl Program code directly added to virtual class. LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
Virtual Class Created from ASPX content LiteralControl Converted to instances of the corresponding server control class for each of these control tags, that will be added to the control tree of this class. LiteralControl The Form control instance is placed directly in the control tree of the class being created; while the TextBox and Label controls are added to the control tree of the Form control. LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
Virtual Class Created from ASPX content LiteralControl “asp” tag-prefix located in config file or Register directive. LiteralControl Class with tag name located in appropriate namespace and assembly. LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
Virtual Class Created from ASPX content __PAGE  System.Web.UI.Page LiteralControl ctrl0  System.Web.UI.LiteralControl LiteralControl Function Code Remember: this class “ultimately” inherits from System.Web.UI.Page ctrl1  System.Web.UI.LiteralControl form1  System.Web.UI.HtmlControls.HtmlForm LiteralControl ctrl2  System.Web.UI.LiteralControl Control IDs TextBox1  System.Web.UI.WebControls.TextBox LiteralControl ctrl3  System.Web.UI.LiteralControl LiteralControl Label1  System.Web.UI.WebControls.Label ctrl4  System.Web.UI.LiteralControl LiteralControl ctrl5  System.Web.UI.LiteralControl LiteralControl End of line
Virtual Class Created from ASPX content LiteralControl LiteralControl This is the next class you’ll see now. LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
Page Class Structure Created by the PageHandlerFactory class Virtual class created from ASPX page. inherits Partial class with control declarations (class name same as code-behind). partials with Code-behind class is other side of partial class. inherits System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
Partial Class Base for virtual class and partial to code-behind Notice the name is the same as the page’s code-behind class. End of line
Page Class Structure Created by the PageHandlerFactory class Virtual class created from ASPX page. inherits Partial class with control declarations (class name same as code-behind). partials with Code-behind class is other side of partial class. inherits System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
Code-Behind Class Other side of the Control Declarations class Inheriting from Page gives you access to a control’s event lifecycle. End of line
Page Class Structure Created by the PageHandlerFactory class Virtual class created from ASPX page. Remember, this entire class hierarchy is the handler returned by the PageHandlerFactory class. It is the HttpApplication pipeline that calls ProcessRequest, kicking off the Page Lifecycle. inherits Partial class with control declarations (class name same as code-behind). ProcessRequest comes from here.  It is from there that the lifecycle events are called. Events for the lifecycle come from here. partials with Code-behind class is other side of partial class. inherits System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
Page (Control) Lifecycle PreInit Init InitComplete CreateChildControls (IsPostBack) LoadViewState/LoadControlState IPostBackDataHandler.LoadPostData PreLoad Load IPostBackDataHandler.RaisePostBackChangedEvent IPostBackEventHandler.RaisePostBackEvent LoadComplete CreateChildControls (!IsPostBack) PreRender DataBind PreRenderComplete SaveViewState/SaveControlState Render Unload Complete List End of line
Most Commonly Known Points Postback only Initialize:OnInit method and Init event Begin tracking ViewState:TrackViewState method Load View State:LoadViewState method Load Postback Data:IPostBackDataHandler.LoadPostdata method Load: OnLoad method and Load event Raise Changed Events:IPostBackDataHandler.RaisePostBackChangedEvent method Raise Postback Event:IPostBackEventHandler.RaisePostBackEvent method PreRender:OnPreRender method and PreRender event Save View State:SaveViewState method Render: Render method Unload:OnUnload method and Unload event End of line
Control Rendering Activated through the Control class’ Render method. Each control is designed to output something to the response buffer. Most controls output HTML. Some controls contain others in their tree. Control rendering involves recursively rendering child controls. Controls don’t need to output anything ScriptManager End of line
Getting a Response “Rendering” uses an HtmlTextWriter stored in the Response object. Response object is part of HttpContext. Writer sent into Render method. After pipeline complete, contents returned up the chain to aspnet_isapi.dllthen http.sys. Results viewed on browser. End of line
Getting a Response You can intercept and/or write directly to the response using Response.Write. Remember classic ASP? Response.WriteFile can be used to output binary information. Can change content type for compatibility with any type of file. Inform browser what’s coming. End of line
Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
Postbacks Invoked by controls on form that trigger the form to “post”. Another HTTP Request, but of a post-type. Certain lifecycle methods only invoked on postback only. In a postback, the Request object’s Form property contains posted data from HTML elements (using their client IDs).
Postbacks Postback only Initialize:OnInit method and Init event Begin tracking ViewState:TrackViewState method Load View State:LoadViewState method Load Postback Data:IPostBackDataHandler.LoadPostdata method Load: OnLoad method and Load event Raise Changed Events:IPostBackDataHandler.RaisePostBackChangedEvent method Raise Postback Event:IPostBackEventHandler.RaisePostBackEvent method PreRender:OnPreRender method and PreRender event Save View State:SaveViewState method Render: Render method Unload:OnUnload method and Unload event End of line
ASCX User Controls Register directive defines tag prefix and name for user control. src points to an ascx file in the current web application. During parsing, virtual class is built just like a page, except the base is called UserControl. Also, added to Page’s Controls collection. UserControl also inherits from Control but does NOT implement IHttpHandler. Usage in an ASPX page (or another ASCX control) is just like a server control. End of line
Master Pages Code-Behind class inherits from MasterPage, which inherits from UserControl. Master directive similar to a Page directive. ASPX page points to a master page file. End of line
Master Pages Control that specifies content to be defined in an ASPX page. Control that wraps content. Each Content control corresponds to a ContentPlaceHolder control. End of line
Master Pages Web Server (IIS) Desktop Browser Browse to Default.aspx PageHandlerFactory commences building of virtual class. MasterPageFile attribute encountered. Parsing shifts to master page file and code-behind. Control tree build and added to virtual class. Parsing returns to ASPX page and Content controls turned to code. Each Content control added to the Controls collection of corresponding ContentPlaceHolder control. End of line
Direct Browsing Note: you cannot browse directly to an ASCX control or a Master page. End of line
ASHX Handlers SimpleHandlerFactory in charge of returning HTTP Handler. End of line
ASHX Handlers PageHandlerFactory: Parses ASPX file, building virtual class as an HTTP Handler, with ProcessRequest kicking off page lifecycle. SimpleHandlerFactory: Takes this handler code and returns is as HTTP Handler. ProcessRequest called in the pipeline as always. End of line
Themes & Skins Contain server control declarations (without IDs) whose properties overwrite those declared on the ASPX page. Control “registration” applies. Either in skin file or in config file. Applied just before Init lifecycle event. Programmatic application MUST be made in PreInit event. Application using Theme attribute occurs last. Application using StyleSheetTheme attribute occurs first. End of line
ASP.NET Ajax More interactive model. Uses JavaScript to invoke Ajax requests. Web Service (WCF) technology can be used to handle response. Ships with controls and components that encapsulate functionality. Ajax Control Toolkit – ships separately Community driven and supported Undergoes Microsoft Scrutiny Better user experience. End of line
ASP.NET MVC Process nearly identical to conventional ASP.NET. It’s still ASP.NET Uses a URL routing engine to parse URLs and invoke appropriate classes. http://site/controller/action/id Pipeline is intercepted by a module tapping into PostResolveRequestCache event. Request is picked up by another handler for processing. Controller classes are sought out and processed (similar to code-behind classes). Appropriate Views parsed and rendered. End of line
Why Custom Modules Background processes URL rewriting or routing Identity persistence for custom providers (or any other kind of persistence) Benchmarking
Why Custom Handlers Image watermarking Dynamic image generation RSS output generation File denial or protection
Tips & Tricks Use your own base page to house common functionality. If overriding On{event} methods, remember that the event-wire-up methods in code-behind fire when you call base On{event}. Example: override OnLoad in a base class, Page_Load in code-behind gets called when you call base.OnLoad. Use <page pageBaseType=   demo Register your server controls in your Web.Config file. Eliminates repeat registrations in ASPX & ASCX files. Eliminates registrations in Skin files. End of line

Mais conteúdo relacionado

Mais procurados

Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsIdo Flatow
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterSachin G Kulkarni
 
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side ProgrammingMilan Thapa
 
Laravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingLaravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingChristopher Pecoraro
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Mario Cardinal
 
Sprint Portlet MVC Seminar
Sprint Portlet MVC SeminarSprint Portlet MVC Seminar
Sprint Portlet MVC SeminarJohn Lewis
 
Server side programming
Server side programming Server side programming
Server side programming javed ahmed
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developersPatrick Savalle
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsBG Java EE Course
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web servicesmwinteringham
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIOverview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIPankaj Bajaj
 

Mais procurados (19)

Web API Basics
Web API BasicsWeb API Basics
Web API Basics
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Hidden Gems in ColdFusion 11
Hidden Gems in ColdFusion 11Hidden Gems in ColdFusion 11
Hidden Gems in ColdFusion 11
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
REST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in CodeigniterREST API Best Practices & Implementing in Codeigniter
REST API Best Practices & Implementing in Codeigniter
 
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side Programming
 
Aspdotnet
AspdotnetAspdotnet
Aspdotnet
 
Laravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingLaravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routing
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
Sprint Portlet MVC Seminar
Sprint Portlet MVC SeminarSprint Portlet MVC Seminar
Sprint Portlet MVC Seminar
 
Web API with ASP.NET MVC by Software development company in india
Web API with ASP.NET  MVC  by Software development company in indiaWeb API with ASP.NET  MVC  by Software development company in india
Web API with ASP.NET MVC by Software development company in india
 
Server side programming
Server side programming Server side programming
Server side programming
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Web api
Web apiWeb api
Web api
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
Understanding and testing restful web services
Understanding and testing restful web servicesUnderstanding and testing restful web services
Understanding and testing restful web services
 
Overview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB APIOverview of Rest Service and ASP.NET WEB API
Overview of Rest Service and ASP.NET WEB API
 

Destaque

前端 JavaScript 相关的小Tips
前端 JavaScript 相关的小Tips前端 JavaScript 相关的小Tips
前端 JavaScript 相关的小Tipsblank zheng
 
Advanced Web Form Practices - Miguel A. Castro
Advanced Web Form Practices - Miguel A. CastroAdvanced Web Form Practices - Miguel A. Castro
Advanced Web Form Practices - Miguel A. CastroMohammad Tayseer
 
Interview with Manhattan Guru
Interview with Manhattan GuruInterview with Manhattan Guru
Interview with Manhattan GuruSteve Do
 
Pni Final Presentation
Pni Final PresentationPni Final Presentation
Pni Final Presentationjohnadam
 

Destaque (6)

前端 JavaScript 相关的小Tips
前端 JavaScript 相关的小Tips前端 JavaScript 相关的小Tips
前端 JavaScript 相关的小Tips
 
Advanced Web Form Practices - Miguel A. Castro
Advanced Web Form Practices - Miguel A. CastroAdvanced Web Form Practices - Miguel A. Castro
Advanced Web Form Practices - Miguel A. Castro
 
G
GG
G
 
Interview with Manhattan Guru
Interview with Manhattan GuruInterview with Manhattan Guru
Interview with Manhattan Guru
 
Maze Game
Maze GameMaze Game
Maze Game
 
Pni Final Presentation
Pni Final PresentationPni Final Presentation
Pni Final Presentation
 

Semelhante a Understanding ASP.NET Under The Cover - Miguel A. Castro

Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applicationsdominion
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnetrsnarayanan
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteorSapna Upreti
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swiftTim Burks
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NETPeter Gfader
 
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
Writing highly scalable WebSocket using the Atmosphere Framework and ScalaWriting highly scalable WebSocket using the Atmosphere Framework and Scala
Writing highly scalable WebSocket using the Atmosphere Framework and Scalajfarcand
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 

Semelhante a Understanding ASP.NET Under The Cover - Miguel A. Castro (20)

RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnet
 
Walther Ajax4
Walther Ajax4Walther Ajax4
Walther Ajax4
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
 
Day7
Day7Day7
Day7
 
Web api
Web apiWeb api
Web api
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
Ajax
AjaxAjax
Ajax
 
T2 Web Framework
T2 Web FrameworkT2 Web Framework
T2 Web Framework
 
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
Writing highly scalable WebSocket using the Atmosphere Framework and ScalaWriting highly scalable WebSocket using the Atmosphere Framework and Scala
Writing highly scalable WebSocket using the Atmosphere Framework and Scala
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
PPT
PPTPPT
PPT
 
Migration from ASP to ASP.NET
Migration from ASP to ASP.NETMigration from ASP to ASP.NET
Migration from ASP to ASP.NET
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 

Understanding ASP.NET Under The Cover - Miguel A. Castro

  • 1. UNDERSTANDING ASP.NETUNDER THE COVERS Miguel A. Castro miguel.castro@idesign.net
  • 2. Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
  • 3.
  • 6. Member of the INETA Speakers Bureau
  • 8. Creator of CodeBreeze
  • 9.
  • 10. Classic ASP Interpreted language Included embedded scripting code mixed into HTML Limited to VBScript Ran in the same process as IIS Inherently not scalable (needed MTS) End of line
  • 11. Classic ASP End of line
  • 12. Walking Upright Designed by Scott Guthrie & Mark Anders Early iteration of ASP.NET Originally known as XSP Not .NET-related – Java based ! Became ASP+ with the design of the CLR Rewritten in C# Renamed when .NET branding introduced End of line
  • 13. What is ASP.NET A framework for developing and delivering information & applications on the web. Known primarily as a page framework. A complete Request/Response management system. Can handle and respond to all sorts of requests on the Internet (or an Intranet). Not a language ! End of line
  • 14. Characteristics of ASP.NET Runs under its own worker process. No longer tied to IIS. Code execution managed by CLR. Code-Behind model allows code separation. Includes state handling facilities. Provides caching functionality. End of line
  • 15. Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
  • 16. Commonly Used Terms Request An HTTP query initiated by a client to a server for the purpose of performing some action. Response A stream of information sent back to a client from the HTTP server that processed the client’s request. ASP.NET Pipeline A series of extensible functionality points which continue the process of a request in order to eventually obtain a response. End of line
  • 17. Commonly Used Terms Page Lifecycle Another series of functionality points that form the process of converting an ASPX page to HTML output. The entire page lifecycle occurs between two pipeline points. Control Model The heart of how ASP.NET builds HTML from compiled classes that represent visual components. End of line
  • 18. Commonly Used Terms HTTP Handlers Classes that are the target of HTTP requests. Assigned by file extension & verb. Map to ISAPI Extensions HTTP Modules Classes that inject mode into the pipeline. Map to ISAPI Filters MVC An design pattern that separates the output design from the information that builds it. End of line
  • 19. Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
  • 20. What Everyone Sees Desktop Browser Web Server (IIS) http://www.microsoft.com/default.aspx Rendered HTML Now the long version… End of line
  • 21. Getting it to .NET (the low level stuff) Web Server (IIS) Web Server (IIS) Kernel Mode Driver:Http API used by IIS http.sys Worker Process(w3wp.exe) – (one per app pool) Worker Process started (one per pool) and if needed, AppDomain is created. aspnet_isapi.dll AppDomain (one per site/VD) Attached to the extension of the request. Unmanaged DLL that loads the CLR and routes requests to the managed runtime classes via COM-compliant interfaces. ISAPIRuntime(ProcessRequest method) HttpRuntime.ProcessRequest Request sent to the ASP.NET runtime for processing. End of line
  • 22. ASP.NET Takes Over HttpRuntime.ProcessRequest Accessible from now until the end of the request processing. Accessible through HttpContext.Current HttpContext created. This serves as an entry point into the request, response, and other accessible variables. Each AppDomain manages multiple instances so they do not conflict with each other (different users or same user with more than one request). An HttpApplication instance is created. HttpApplication This is where it starts to mean something to you, the developer. Init method starts pipeline processing. End of line
  • 23. Entering the Pipeline Pipeline kicked off in the Init method. HttpApplication BeginRequest Performs event processing. AuthenticateRequest / Post AuthorizeRequest / Post Checks hooks from Global.asax class. ResolveRequestCache / Post Checks hooks from external HTTP Modules. MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post ReleaseRequestState / Post UpdateRequestCache / Post LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
  • 24. Entering the Pipeline HttpApplication BeginRequest AuthenticateRequest / Post AuthorizeRequest / Post ResolveRequestCache / Post MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post ReleaseRequestState / Post UpdateRequestCache / Post LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
  • 25. Pipeline Events of Interest HttpApplication Provide URL-Rewriting functionality. BeginRequest AuthenticateRequest / Post Repopulate HttpContext.Current.User with stored principal. Page authentication occurs here. AuthorizeRequest / Post ResolveRequestCache / Post MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post Determine whether to use cached response. ReleaseRequestState / Post UpdateRequestCache / Post Any event can be hooked in Global.asax or in an HTTP Module. LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
  • 26. HTTP Modules Classes that implement IHttpModule. MyModule : IHttpModule Delegate-based Properties in HttpApplication instance can be wired up. Method functionality equivalent to hooking event in Global.asax Event hooks in modules checked during pipeline processing. End of line
  • 27. AuthenticateRequest WindowsAuthenticationModule FormsAuthenticationModule UrlAuthenticationModule FileAuthorizationModule ServiceModel SessionStateModule OutputCacheModule AuthenticateRequest EndRequest AuthorizeRequest AuthorizeRequest PostAuthenticateRequest AcquireRequestState AcquireRequestState ReleaseRequestState EndRequest ASP.NET HTTP Modules of Interest End of line
  • 28. Module Installation Any level in the Config chain You do know what the Config chain is, right? End of line
  • 29. The Process Continues HttpApplication Just before this event: Proper HTTP Handler located based on request’s extension. BeginRequest AuthenticateRequest / Post Handlers provide necessary processing in order to create a response. AuthorizeRequest / Post ResolveRequestCache / Post MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post ReleaseRequestState / Post UpdateRequestCache / Post LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
  • 30. HTTP Handlers Classes that implement IHttpHandler. Determines if the handler instance can be reused by another request. MyHandler : IHttpHandler Functionality assigned to this particular handler. Remember the HttpContext contains all accessible variables, including Response. End of line
  • 31. HTTP Handler Factories Can also implement IHttpHandlerFactory. Allows the instantiation of any handler based on specific conditioning scenarios. MyHandlerFactory : IHttpHandlerFactory End of line
  • 32. Characteristics of an HTTP Handler Access to current HttpContext. Request is in there (as is the Response) ! Handlers are wired to extensions (aspx, etc.). Every handler is responsible for what the response is going to be for a request. ASPX requests expect an HTML response. Config requests expect a “forbidden” response. End of line
  • 33. Handler Execution HttpApplication BeginRequest AuthenticateRequest / Post AuthorizeRequest / Post The determined handler is processed between the PreRequestHandlerExecute and PostRequestHandlerExecute. ResolveRequestCache / Post MapRequestHandler / Post AcquireRequestState / Post PreRequestHandlerExecute / Post ReleaseRequestState / Post UpdateRequestCache / Post LogRequest / Post EndRequest PreSendRequestHeaders PreSendRequestContent End of line
  • 34. Handler Installation Handler factory that returns and executes the handler that will convert an ASPX page to HTML output. Any level in the Config chain End of line
  • 35. The PageHandlerFactory Class Implements IHttpHandlerFactory. GetHandler method returns an IHttpHandler in the form of System.Web.UI.Page-derived class hierarchy. Page class implements IHttpHandler. Page class inherits from Control. Control contains events/methods for the “Page Event Lifecycle”. PageHandlerFactory creates a class structure out of your request. End of line
  • 36. Page Class Structure Follows the structure of an ASP.NET Server Control. Referred to as Page-Gen Class. Created by the PageHandlerFactory class Virtual class created from ASPX page. Controls created based on ASPX content. inherits Partial class with control declarations (class name same as code-behind). partials with Code-behind class is other side of partial class. This is why you can tap into events from your code-behind. inherits ProcessRequest method calls lifecycle events in Control. System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
  • 37. Page Class Structure Created by the PageHandlerFactory class Virtual class created from ASPX page. inherits Partial class with control declarations (class name same as code-behind). partials with Code-behind class is other side of partial class. inherits System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
  • 38. Virtual Class Created from ASPX content Determines language to be used to generate page-gen class. Specifies the partial class to serve as the code-behind. Optional: Name of the code-file for Visual Studio. End of line
  • 39. Virtual Class Created from ASPX content LiteralControl Converted to instances of System.Web.UI.LiteralControl that are added to the control tree of this class. Remember, this class will ultimately inherit from System.Web.UI.Control LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
  • 40. Virtual Class Created from ASPX content LiteralControl LiteralControl Program code directly added to virtual class. LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
  • 41. Virtual Class Created from ASPX content LiteralControl Converted to instances of the corresponding server control class for each of these control tags, that will be added to the control tree of this class. LiteralControl The Form control instance is placed directly in the control tree of the class being created; while the TextBox and Label controls are added to the control tree of the Form control. LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
  • 42. Virtual Class Created from ASPX content LiteralControl “asp” tag-prefix located in config file or Register directive. LiteralControl Class with tag name located in appropriate namespace and assembly. LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
  • 43. Virtual Class Created from ASPX content __PAGE System.Web.UI.Page LiteralControl ctrl0 System.Web.UI.LiteralControl LiteralControl Function Code Remember: this class “ultimately” inherits from System.Web.UI.Page ctrl1 System.Web.UI.LiteralControl form1 System.Web.UI.HtmlControls.HtmlForm LiteralControl ctrl2 System.Web.UI.LiteralControl Control IDs TextBox1 System.Web.UI.WebControls.TextBox LiteralControl ctrl3 System.Web.UI.LiteralControl LiteralControl Label1 System.Web.UI.WebControls.Label ctrl4 System.Web.UI.LiteralControl LiteralControl ctrl5 System.Web.UI.LiteralControl LiteralControl End of line
  • 44. Virtual Class Created from ASPX content LiteralControl LiteralControl This is the next class you’ll see now. LiteralControl LiteralControl LiteralControl LiteralControl LiteralControl End of line
  • 45. Page Class Structure Created by the PageHandlerFactory class Virtual class created from ASPX page. inherits Partial class with control declarations (class name same as code-behind). partials with Code-behind class is other side of partial class. inherits System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
  • 46. Partial Class Base for virtual class and partial to code-behind Notice the name is the same as the page’s code-behind class. End of line
  • 47. Page Class Structure Created by the PageHandlerFactory class Virtual class created from ASPX page. inherits Partial class with control declarations (class name same as code-behind). partials with Code-behind class is other side of partial class. inherits System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
  • 48. Code-Behind Class Other side of the Control Declarations class Inheriting from Page gives you access to a control’s event lifecycle. End of line
  • 49. Page Class Structure Created by the PageHandlerFactory class Virtual class created from ASPX page. Remember, this entire class hierarchy is the handler returned by the PageHandlerFactory class. It is the HttpApplication pipeline that calls ProcessRequest, kicking off the Page Lifecycle. inherits Partial class with control declarations (class name same as code-behind). ProcessRequest comes from here. It is from there that the lifecycle events are called. Events for the lifecycle come from here. partials with Code-behind class is other side of partial class. inherits System.Web.UI.Page inherits implements System.Web.UI.Control IHttpHandler End of line
  • 50. Page (Control) Lifecycle PreInit Init InitComplete CreateChildControls (IsPostBack) LoadViewState/LoadControlState IPostBackDataHandler.LoadPostData PreLoad Load IPostBackDataHandler.RaisePostBackChangedEvent IPostBackEventHandler.RaisePostBackEvent LoadComplete CreateChildControls (!IsPostBack) PreRender DataBind PreRenderComplete SaveViewState/SaveControlState Render Unload Complete List End of line
  • 51. Most Commonly Known Points Postback only Initialize:OnInit method and Init event Begin tracking ViewState:TrackViewState method Load View State:LoadViewState method Load Postback Data:IPostBackDataHandler.LoadPostdata method Load: OnLoad method and Load event Raise Changed Events:IPostBackDataHandler.RaisePostBackChangedEvent method Raise Postback Event:IPostBackEventHandler.RaisePostBackEvent method PreRender:OnPreRender method and PreRender event Save View State:SaveViewState method Render: Render method Unload:OnUnload method and Unload event End of line
  • 52. Control Rendering Activated through the Control class’ Render method. Each control is designed to output something to the response buffer. Most controls output HTML. Some controls contain others in their tree. Control rendering involves recursively rendering child controls. Controls don’t need to output anything ScriptManager End of line
  • 53. Getting a Response “Rendering” uses an HtmlTextWriter stored in the Response object. Response object is part of HttpContext. Writer sent into Render method. After pipeline complete, contents returned up the chain to aspnet_isapi.dllthen http.sys. Results viewed on browser. End of line
  • 54. Getting a Response You can intercept and/or write directly to the response using Response.Write. Remember classic ASP? Response.WriteFile can be used to output binary information. Can change content type for compatibility with any type of file. Inform browser what’s coming. End of line
  • 55. Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
  • 56. Postbacks Invoked by controls on form that trigger the form to “post”. Another HTTP Request, but of a post-type. Certain lifecycle methods only invoked on postback only. In a postback, the Request object’s Form property contains posted data from HTML elements (using their client IDs).
  • 57. Postbacks Postback only Initialize:OnInit method and Init event Begin tracking ViewState:TrackViewState method Load View State:LoadViewState method Load Postback Data:IPostBackDataHandler.LoadPostdata method Load: OnLoad method and Load event Raise Changed Events:IPostBackDataHandler.RaisePostBackChangedEvent method Raise Postback Event:IPostBackEventHandler.RaisePostBackEvent method PreRender:OnPreRender method and PreRender event Save View State:SaveViewState method Render: Render method Unload:OnUnload method and Unload event End of line
  • 58. ASCX User Controls Register directive defines tag prefix and name for user control. src points to an ascx file in the current web application. During parsing, virtual class is built just like a page, except the base is called UserControl. Also, added to Page’s Controls collection. UserControl also inherits from Control but does NOT implement IHttpHandler. Usage in an ASPX page (or another ASCX control) is just like a server control. End of line
  • 59. Master Pages Code-Behind class inherits from MasterPage, which inherits from UserControl. Master directive similar to a Page directive. ASPX page points to a master page file. End of line
  • 60. Master Pages Control that specifies content to be defined in an ASPX page. Control that wraps content. Each Content control corresponds to a ContentPlaceHolder control. End of line
  • 61. Master Pages Web Server (IIS) Desktop Browser Browse to Default.aspx PageHandlerFactory commences building of virtual class. MasterPageFile attribute encountered. Parsing shifts to master page file and code-behind. Control tree build and added to virtual class. Parsing returns to ASPX page and Content controls turned to code. Each Content control added to the Controls collection of corresponding ContentPlaceHolder control. End of line
  • 62. Direct Browsing Note: you cannot browse directly to an ASCX control or a Master page. End of line
  • 63. ASHX Handlers SimpleHandlerFactory in charge of returning HTTP Handler. End of line
  • 64. ASHX Handlers PageHandlerFactory: Parses ASPX file, building virtual class as an HTTP Handler, with ProcessRequest kicking off page lifecycle. SimpleHandlerFactory: Takes this handler code and returns is as HTTP Handler. ProcessRequest called in the pipeline as always. End of line
  • 65. Themes & Skins Contain server control declarations (without IDs) whose properties overwrite those declared on the ASPX page. Control “registration” applies. Either in skin file or in config file. Applied just before Init lifecycle event. Programmatic application MUST be made in PreInit event. Application using Theme attribute occurs last. Application using StyleSheetTheme attribute occurs first. End of line
  • 66. ASP.NET Ajax More interactive model. Uses JavaScript to invoke Ajax requests. Web Service (WCF) technology can be used to handle response. Ships with controls and components that encapsulate functionality. Ajax Control Toolkit – ships separately Community driven and supported Undergoes Microsoft Scrutiny Better user experience. End of line
  • 67. ASP.NET MVC Process nearly identical to conventional ASP.NET. It’s still ASP.NET Uses a URL routing engine to parse URLs and invoke appropriate classes. http://site/controller/action/id Pipeline is intercepted by a module tapping into PostResolveRequestCache event. Request is picked up by another handler for processing. Controller classes are sought out and processed (similar to code-behind classes). Appropriate Views parsed and rendered. End of line
  • 68. Why Custom Modules Background processes URL rewriting or routing Identity persistence for custom providers (or any other kind of persistence) Benchmarking
  • 69. Why Custom Handlers Image watermarking Dynamic image generation RSS output generation File denial or protection
  • 70. Tips & Tricks Use your own base page to house common functionality. If overriding On{event} methods, remember that the event-wire-up methods in code-behind fire when you call base On{event}. Example: override OnLoad in a base class, Page_Load in code-behind gets called when you call base.OnLoad. Use <page pageBaseType= demo Register your server controls in your Web.Config file. Eliminates repeat registrations in ASPX & ASCX files. Eliminates registrations in Skin files. End of line
  • 71. Tips & Tricks Remove HTTP Modules that you don’t need If file protection necessary, add file extension (ZIP) to registered extensions in IIS. Bring them into the pipeline for protection and controlled exposure. Presentation available on my site. End of line
  • 72. Tips & Tricks Turn ViewState off in controls that don’t need them – especially grids. In 4.0 the model can be reversed. More compact in 4.0. Override LoadPageStateFromPersistenceMedium & SavePageStateToPersistenceMedium to alter where and how ViewState is saved.
  • 73. Tips & Tricks Deployment Mode In <system.web> <deployment retail=“true” /> Turns debugging, tracing, and detailed errors OFF Machine.Config ONLY Way Advanced PageParserFilter abstract base class Lets you govern the behavior of the ASP.NET Page Parser
  • 74. Agenda Defining ASP.NET Terms & Buzzwords A Request-to-Response Walkthrough Additional Technologies Summary
  • 75. What To Take Away From This ASP.NET does much more than serve pages. Decoupled architecture allows flexible hosting. Pipeline and Event cycle – two different things. Extensible architecture allows opportunities for interception and alteration. Module and Handler model enforce encapsulation and reusability. Be mindful of how much is happenning behind the scenes. End of line
  • 76. References Great Wikipedia entry http://en.wikipedia.org/wiki/ASP+ Article: How ASP.NET Works http://www.west-wind.com/presentations/howaspnetworks/howaspnetworks.asp Code Magazine – Nov/Dec 2005 Rick Strahl
  • 77. References Article: Truly Understanding ViewState http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx Dave Reed Understanding ASP.NET Internals http://grokable.com/teched-2007-presentation-slides-and-demos/ Rob Howard
  • 78. Essential ASP.NET 2.0 Addison-Wesley Fritz Onion & Keith Brown My Site & Email: www.dotnetdude.com miguel.castro@idesign.net