590 likes | 820 Views
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
E N D
DEV410Inside 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 • INETA Speaker’s Bureau • BEA Technical Director • Web Services Program Advisor, UCSD • Blog: www.dasblonde.net
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
Agenda • IIS & ASP.NET Configuration • HTTP Modules • HTTP Handler Factories and HTTP Handlers • SOAP Extensions
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
IIS & ASP.NETRuntime Configuration • .NET extensions are configured to be handled by aspnet_isapi.dll
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
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>
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>
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
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
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
HTTP Pipeline Components • Configurable components: • HTTP Handler Factories • HTTP Handlers • HTTP Modules • SOAP Extensions • Use individually, or combined • Configure per application, or globally
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
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
Agenda • IIS & ASP.NET Configuration • HTTP Modules • HTTP Handler Factories and HTTP Handlers • SOAP Extensions
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
HTTP Modules • WindowsAuthenticationModule • FormsAuthentication • PassportAuthenticationModule • FileAuthorizationModule • UrlAuthorizationModule • SessionStateModule
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>
HTTP ModulesIHttpModule • Modules implement IHttpModule Interface IHttpModule { void Init( HttpApplication context ); void Dispose(); }
HTTP ModulesInitialization • Register for events during Init() protected void Init() { application.PreRequestHandlerExecute += (new EventHandler(this.Application_PreRequestHandlerExecute)); application.PostRequestHandlerExecute += (new EventHandler(this.Application_PostRequestHandlerExecute)); }
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; }
HTTP ModulesApplication Events ASP.NET HTTP Modules Page Resource BeginRequest() AuthenticateRequest() AuthorizeRequest() ResolveRequestCache() AcquireRequestState() PreRequestHandlerExecute() HTTP GET somepage.aspx PostRequestHandlerExecute() ReleaseRequestState() UpdateRequestCache() EndRequest()
Agenda • IIS & ASP.NET Configuration • HTTP Modules • HTTP Handler Factories and HTTP Handlers • SOAP Extensions
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
HTTP Handler Factories • System.Web.UI.PageHandlerFactory • System.Web.Services.Protocols. WebServiceHandlerFactory • System.Runtime.Remoting.Channels.Http. HttpRemotingHandlerFactory
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>
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 ); }
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()
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()
HTTP Handlers • System.Web.HttpForbiddenHandler • System.Web.StaticFileHandler • System.Web. • HttpMethodNotAllowedHandler • System.Web.Handlers.TraceHandler • System.Web.UI.Page
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>
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;} }
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;} } }
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 ); }
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 {…}
Agenda • IIS & ASP.NET Configuration • HTTP Modules • HTTP Handler Factories and HTTP Handlers • SOAP Extensions
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
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
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
WebServiceHandler • Base class to Web service handlers • WebServiceHandlerFactory handles delegation to correct handler WebServiceHandler SyncSessionlessHandler SyncSessionHandler AsyncSessionlessHandler AsyncSessionHandler
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()
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
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 ); }
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
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
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
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; }