1 / 58

DEV410 Inside the ASP.NET Runtime - Intercepting HTTP Requests

DEV410 Inside the ASP.NET Runtime - Intercepting HTTP Requests. Michele Leroux Bustamante Principal Software Architect IDesign Inc. Speaker BIO. Principal Software Architect, IDesign, www.idesign.net Microsoft Regional Director, www.microsoft.com/rd Microsoft MVP – XML Web Services

jacie
Download Presentation

DEV410 Inside the ASP.NET Runtime - Intercepting HTTP Requests

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. DEV410Inside the ASP.NET Runtime - Intercepting HTTP Requests Michele Leroux Bustamante Principal Software Architect IDesign Inc.

  2. Speaker BIO • Principal Software Architect, IDesign, www.idesign.net • Microsoft Regional Director, www.microsoft.com/rd • Microsoft MVP – XML Web Services • INETA Speaker’s Bureau • BEA Technical Director • Web Services Program Advisor, UCSD • Blog: www.dasblonde.net

  3. What we will cover: • How IIS passes requests to ASP.NET • How to configure the ASP.NET pipeline to intercept requests, and why you’d want to • How to create useful custom pipeline components • HTTP Modules • Handler Factories and Handlers • SOAP Extensions

  4. Agenda • IIS & ASP.NET Configuration • HTTP Modules • HTTP Handler Factories and HTTP Handlers • SOAP Extensions

  5. IIS & ASP.NETRuntime Configuration • IIS passes HTTP requests to ASP.NET through an unmanaged ISAPI extension • This is the “hook” between IIS and the ASP.NET HTTP runtime • Resource extensions are configured in IIS to be handled by ASP.NET • Default configuration excludes *.xml, *.html, graphic file extensions and more

  6. IIS & ASP.NETRuntime Configuration • .NET extensions are configured to be handled by aspnet_isapi.dll

  7. IIS & ASP.NETRequest Workflow IIS ASP.NET Runtime Application *.asmx HTTP Request aspnet_isapi.dll Machine.config Web.config *.asp asp.dll HTTP Response Process Request

  8. ASP.NET ConfigurationMachine.config • Machine.config defines default handlers or handler factories to manage requests <httpHandlers> <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/> <add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, …/> <add verb="*" path="*.soap" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, …/> <add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler"/> </httpHandlers>

  9. ASP.NET ConfigurationWeb.config • Web.config may alter Machine.config settings at the application level • HTTP Handlers can be chosen by: • Verb: POST/GET • Path: by extension, by specific URL <httpHandlers> <add verb=“GET" path="*.xml" type=“DotNetDashboard.Web.FileDownloadHandler, DotNetDashboard.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxx"/> <add verb="*" path=“displayImage.aspx" type=“DotNetDashboard.Web.ImageFormatter, DotNetDashboard.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxx” /> <add verb="*" path=“*.xls” type="System.Web.HttpForbiddenHandler"/> </httpHandlers>

  10. IIS & ASP.NETRequest Workflow IIS ASP.NET Runtime Application *.asmx HTTP Request aspnet_isapi.dll Machine.config Web.config *.asp asp.dll IHttpHandlerFactory IHttpHandler HTTP Response Process Request

  11. IIS 5.0 and ASP.NET IIS 5.0 ASP.NET aspnet_wp.exe Thread Pool Application Domain HttpApplication Pooled Inetinfo.exe HttpModules HttpHandler aspnet_isapi.dll HttpHandler

  12. IIS 6.0 and ASP.NET IIS 6.0 ASP.NET w3wp.exe aspnet_wp.exe aspnet_wp.exe http.sys Application Domain HttpHandler inetinfo.exe

  13. HTTP Pipeline Components • Configurable components: • HTTP Handler Factories • HTTP Handlers • HTTP Modules • SOAP Extensions • Use individually, or combined • Configure per application, or globally

  14. HTTP Modules HTTP Modules HTTP Modules Pipeline Components Page Request IIS ASP.NET Runtime ASPNET_ISAPI.DLL HTTP Handler/Page HTTP Request HTTP Handler Factory HTTP Response

  15. HTTP Modules HTTP Modules HTTP Modules Pipeline ComponentsWeb Method Request IIS ASP.NET Runtime ASPNET_ISAPI.DLL Web Service Method HTTP Request SOAP Extension HTTP Handler Factory HTTP Handler/ WebServicesHandler SOAP Extension SOAP Extension HTTP Response

  16. Agenda • IIS & ASP.NET Configuration • HTTP Modules • HTTP Handler Factories and HTTP Handlers • SOAP Extensions

  17. HTTP Modules • Leverage an event-driven model to interact with Web applications • Can interact with every HTTP request • Useful for: • Custom authorization • Global error handler • Implementing caching or other utilities • Request diagnostics

  18. HTTP Modules • WindowsAuthenticationModule • FormsAuthentication • PassportAuthenticationModule • FileAuthorizationModule • UrlAuthorizationModule • SessionStateModule

  19. HTTP ModulesConfiguration • Configured in <httpModules> • Instantiated in order configured • Intercept events before the application object (global.asax) receives them <system.web> … <httpModules> <add name=“EventModule" type=“WebHandlers.EventModule, WebHandlers"/> </httpModules> … </system.web>

  20. HTTP ModulesIHttpModule • Modules implement IHttpModule Interface IHttpModule { void Init( HttpApplication context ); void Dispose(); }

  21. HTTP ModulesInitialization • Register for events during Init() protected void Init() { application.PreRequestHandlerExecute += (new EventHandler(this.Application_PreRequestHandlerExecute)); application.PostRequestHandlerExecute += (new EventHandler(this.Application_PostRequestHandlerExecute)); }

  22. HTTP ModulesEvent Handlers • Events based on EventHandler delegate • Access to HttpApplication object • Can also publish events to listening applications within the module’s scope private void Application_PreRequestHandlerExecute(Object source, EventArgs e) { HttpApplication app = (HttpApplication)source; }

  23. HTTP ModulesApplication Events ASP.NET HTTP Modules Page Resource BeginRequest() AuthenticateRequest() AuthorizeRequest() ResolveRequestCache() AcquireRequestState() PreRequestHandlerExecute() HTTP GET somepage.aspx PostRequestHandlerExecute() ReleaseRequestState() UpdateRequestCache() EndRequest()

  24. HTTP Module

  25. Agenda • IIS & ASP.NET Configuration • HTTP Modules • HTTP Handler Factories and HTTP Handlers • SOAP Extensions

  26. HTTP Handler Factories & HTTP Handlers • Components configured to handle requests for specific resources • HTTP handler factories return an HTTP handler to process the request • Or, you can configure the HTTP handler directly • Useful for: • Intercepting requests for specific resources • Overriding how requests are processed • Formatting requests for custom types

  27. HTTP Handler Factories • System.Web.UI.PageHandlerFactory • System.Web.Services.Protocols. WebServiceHandlerFactory • System.Runtime.Remoting.Channels.Http. HttpRemotingHandlerFactory

  28. HTTP Handler FactoriesConfiguration • Register in <httpHandlers> • Can override in application Web.config <httpHandlers> <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/> <add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory, System.Web.Services, …/> </httpHandlers>

  29. HTTP Handler Factories IHttpHandlerFactory • Implement IHttpHandlerFactory • GetHandler() • Returns IHttpHandler type • Can access HttpContext and related info • ReleaseHandler() • Cleanup! interface IHttpHandlerFactory { IHttpHandler GetHandler( HttpContext context, string requestType, string url, string pathTranslated ); void ReleaseHandler( IHttpHandler handler ); }

  30. HTTP Handler FactoryPage Request ASP.NET HTTP Modules Handler Factory Handler Page Resource BeginRequest() AuthenticateRequest() AuthorizeRequest() ResolveRequestCache() GetHandler() AcquireRequestState() PreRequestHandlerExecute() ProcessRequest() HTTP GET somepage.aspx PostRequestHandlerExecute() ReleaseRequestState() UpdateRequestCache() EndRequest()

  31. HTTP Handler FactoryWeb Service Method ASP.NET HTTP Modules Handler Factory Handler Web Service BeginRequest() AuthenticateRequest() AuthorizeRequest() ResolveRequestCache() GetHandler() AcquireRequestState() PreRequestHandlerExecute() ProcessRequest() WebMethod() PostRequestHandlerExecute() ReleaseRequestState() UpdateRequestCache() EndRequest()

  32. HTTP Handlers • System.Web.HttpForbiddenHandler • System.Web.StaticFileHandler • System.Web. • HttpMethodNotAllowedHandler • System.Web.Handlers.TraceHandler • System.Web.UI.Page

  33. HTTP HandlersConfiguration • Can directly configure IHttpHandler instead of IHttpHandlerFactory • Factory used when specific handler may vary per request specifics <httpHandlers> <add verb="*" path="trace.axd" type="System.Web.Handlers.TraceHandler"/> <add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler"/> <add verb="GET,HEAD" path="*" type="System.Web.StaticFileHandler"/> </httpHandlers>

  34. HTTP HandlersIHttpHandler • Implement IHttpHandler • ProcessRequest() • Invoked by HttpRuntime • Handle the request accordingly • IsReusable • If resource can be shared, return true Interface IHttpHandler { void ProcessRequest(HttpContext context ); bool IsReusable {get;} }

  35. HTTP Handler Factories & Handlers

  36. HTTP HandlersAccessing Session • To access Session from a custom handler, implement marker interface, IRequiresSessionState class CustomHandler: IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context ) { object somdData = context.Session[“data”]; … } public bool IsReusable { get { return true;} } }

  37. HTTP HandlersAsynchronous Handlers • Asynchronous design pattern • Offloads request to a new thread • Frees thread from the application thread pool for better performance • Limited gains without scalable architecture interface IHttpAsyncHandler : IHttpHandler { IAsyncResult BeginProcessRequest( HttpContext context, AsyncCallback cb, object extraData ); void EndProcessRequest(IAsyncResult result ); }

  38. HTTP Handlers*.ASHX • Handlers may be defined in an .ashx file • Flexible, lightweight implementation • No IIS configuration required • With or without code-behind <add verb="*" path="*.ashx" type="System.Web.UI.SimpleHandlerFactory" /> <%@ WebHandler Language="C#" Class=“MyCustomHandler" %> public class MyCustomHandler: IHttpHandler {…}

  39. Agenda • IIS & ASP.NET Configuration • HTTP Modules • HTTP Handler Factories and HTTP Handlers • SOAP Extensions

  40. Message Serialization • ASP.NET uses XmlSerializer to serialize/deserialize SOAP messages Client Application Web Service SOAP Request Client Proxy Web Method Deserialize Serialize XML Parameters Parameters Serialize Deserialize SOAP Response Return Value Return Value XML

  41. SOAP Extensions IIS ASP.NET Runtime Log Validate/Transform ASPNET_ISAPI.DLL Web Service Method Decompress Decrypt Authorize/Authenticate HTTP Request HTTP Response SOAP Extensions

  42. SOAP Extensions • Provide a mechanism to interact with processing Web service messages • Specifically serialization and deserialization • For example: • Encyrypt/decrypt SOAP messages • Transform messages before/after serialization/deserialization processes • Log requests

  43. WebServiceHandler • Base class to Web service handlers • WebServiceHandlerFactory handles delegation to correct handler WebServiceHandler SyncSessionlessHandler SyncSessionHandler AsyncSessionlessHandler AsyncSessionHandler

  44. SOAP ExtensionSerialization/Deserialization ASP.NET HTTP Modules Handler Factory Handler SOAP Extension Web Service BeginRequest() AuthenticateRequest() AuthorizeRequest() ResolveRequestCache() GetHandler() AcquireRequestState() PreRequestHandlerExecute() ProcessRequest() BeforeDeserialize AfterDeserialize WebMethod() BeforeSerialize AfterSerialize PostRequestHandlerExecute() ReleaseRequestState() UpdateRequestCache() EndRequest()

  45. SOAP Extension Implementation • Create an extension class that derives from SoapExtension • Create attribute class that derives from SoapExtensionAttribute • Configure the extension: • For entire Web service in Web.config • For specific method using extension attribute

  46. SoapExtension Class • Create a custom extension class, extend SoapExtension Class SoapExtension { public abstract object GetInitializer( Type serviceType ); public abstract object GetInitializer( LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute ); public abstract void Initialize( object initializer ); public virtual Stream ChainStream( Stream stream ); public abstract void ProcessMessage( SoapMessage message ); }

  47. SOAP Extension Workflow ASP.NET SOAP Extension Web Service Once per application GetInitializer() Initialize() ChainStream() ProcessMessage() – Before Deserialize ProcessMessage() – After Deserialize Each method request [WebMethod] ChainStream() ProcessMessage() – Before Serialize ProcessMessage() – After Serialize

  48. ProcessMessage() • Access to SoapMessage at various serialization stages • SOAP extensions on the Web server: • On request, message is deserialized • SoapMessageStage.BeforeDeserialize • SoapMessageStage.AfterDeserialize • On response, message is serialized: • SoapMessageStage.BeforeSerialize • SoapMessageStage.AfterSerialize

  49. ProcessMessage() • SOAP extensions on the Web client: • On request, message is serialized • SoapMessageStage.BeforeSerialize • SoapMessageStage.AfterSerialize • On response, message is deserialized: • SoapMessageStage.BeforeDeserialize • SoapMessageStage.AfterDeserialize

  50. ChainStream() • Provides access to the memory buffer of the SOAP request • Do not have to override this, default behavior returns original stream • Can return a new stream object for ASP.NET to reference public override Stream ChainStream( Stream stream ) { m_oldStream = stream; m_newStream = new MemoryStream(); return m_newStream; }

More Related