SlideShare a Scribd company logo
Advanced Asp.Net Concepts And Constructs
IIS and ASP.NET Integration – Deep Dive


    HTTP Modules


    HTTP Handlers


    Virtual Path Provider


    URL Rewriting


    Response Filters


    Configuration Runtime API

Extending web servers by means of installing

    some components
     Internet Server API – ISAPI (Microsoft)
     Netscape Server API – NSAPI (Netscape)
    IIS is an ISAPI compliant web server

     Extension possible through ISAPI Filters and
      Extensions (both are Win 32 DLLs)
    Application Mapping in IIS maps the request to

    an ISAPI Extension by mapping the request
    extension to a Win 32 DLL.
The integration b/w IIS and ASP.NET occurs through the

    Application Mapping – ASP.NET is an ISAPI Extension!
IIS

     Receives the request
     Authenticates the request and attaches a security
      token (identity) to it.
       For authenticated requests, it is the Windows identity of
        the user connecting to IIS (e.g. Domainusername)
       For anonymous requests, it is your old friend
        IUSR_Machinename or whatever account is specified in
        IIS for anonymous requests.
     Forwards the request along with the token to
      aspnet_isapi.dll
aspnet_isapi.dll

     Since it’s a DLL, it will be mapped into the address
      space of the web server process which runs under the
      SYSTEM account! Not good!
     That’s why it does not do much in terms of processing
      the request.
     Forwards the request to the ASP.NET Worker Process.
Worker Process

     Provides housing for the worker threads
     Aspnet_wp.exe
       IIS 5.0 and IIS 5.1
       The process identity is determined by the <processModel>
        node in the machine.config file
     W3wp.exe
       IIS 6.0 – Worker Process Isolation Mode
         The process identity is not determined by the <processModel>
          node; in-fact almost all of the settings defined by this node are
          ignored.
         The process identity is determined by the Application Pool
          identity.
       IIS 6.0 – IIS 5 Isolation Mode
         Works like IIS 5
Identities

     Process Identity – discussed earlier
     Worker Thread Identity!
       Why is it needed?
         To answer that, think about what would happen if there is
          no thread identity?
       What could be the thread identity?
         The thread identity could be one of the following:
           Identity of the Worker Process.
           Identity passed by IIS to ASP.NET.
           Identity specified in the <identity> node in the web.config.
Identities

     Thread Identity
       How is it determined which identity out of the three will
        be used?
         Identity of the Worker Process
           Impersonation is disabled <identity impersonate=“false”/>
            (the default setting)
         Identity passed by IIS
           Impersonation is enabled <identity impersonate=“true”/>
         Identity specified in the <identity> node in the web.config
           Impersonation is enabled and a specific identity has been
            specified in the web.config file <identity impersonate=“true”
            userName=“manny” password=“mannypwd”/>
A class that participates in the ASP.NET request

    processing pipe-line (by virtue of registering for
    the events)
    Provides high level of componentization


    ASP.NET implements some of its functionalities

    using HTTP modules
Implements the IHttpModule interface

Configure the module using web.config file





    ASP.NET Modules

Advanced Asp.Net Concepts And Constructs
Tips/Tricks

     Modules are called for each and every request which is
      handled by ASP.NET for that application; no
      configuration to run the HTTP module for selective
      requests
       Write custom if-then-else checks in the module code.
     The events raised by HTTP modules and the
      HttpApplication class are captured in the Global.asax
       Convention: ModuleName_EventName
       Examples: Session_Start, Session_End,
        CustomModule_MyCustomEvent
       That means the custom modules can also raise events
        and those events can be captured in the Global.asax file!
Tips/Tricks

     Did you know that the events raised by modules can
      also be captured by other modules? How to do that?
                                                    HttpApplication
                                                     maintains the
                                                   modules collection


                                                   Module name from
                                                     the config file




                                                   Event raised by the
                                                    Session module
Tips/Tricks

     HTTP modules are called in the order in which the
      modules have been defined in the web.config file.
       For example, WSS SharePoint hijacks the ASP.NET pipe-
        line by clearing all of the existing modules and installing
        a custom module as the very first module!




                                             WSS/MOSS module installed as the 1st
                                             module in the ASP.NET page processing
                                                            pipeline
Tips/Tricks

     ASP.NET framework changes its behavior slightly for
      the .asmx requests, which in turn affects the way
      HTTP modules behave.
       Unhandled exception in an ASP.NET web page or an
        HttpHandler raises the Error event as usual.
       Unhandled exception in an ASMX web service gets
        translated into a SOAP Fault! You would have to write
        SOAP Extension to deal with it.
Practical uses for HTTP modules

     Application wide exception handling
Practical uses for HTTP modules

     Referrer tracking
Practical uses for HTTP modules

     URL Rewriting
Practical use of HTTP modules

     Security
       Force the user to change password @ the time of first
        login.
       Force the user to accept the terms and conditions
A class that is the final destination for a request

    that comes to ASP.NET
    Must implement the IHttpHandler interface


    ASP.NET uses handlers for implementing most of

    its functionality
Use the <httpHandlers> node to register any

    handlers


    There are three ways of using a handler

     For processing a custom request (e.g. handler for
      processing .rdnug files)
     For processing requests to an already mapped
      ASP.NET extension (e.g. image.axd)
     Similar to the 2nd option – Directly calling a handler
      without using any custom or commonly used ASP.NET
      extensions – generic handler!
Processing a custom request

     Allows you to define your own custom extension
     Requires changes to IIS! Not good for hosted
      applications.
     Steps required
       Implement the IHttpHandler interface on a class
       Add a new Application Mapping for the new extension in
        order for the requests to be re-reroute to ASP.NET
       Add the handler to the web.config file

       Client syntax would be as follows
         http://site/virtualdirectory/test.rdnug
Advanced Asp.Net Concepts And Constructs
Process an already mapped extension

     Allow you to re-use an already mapped ASP.NET extension
     No changes to the IIS meta-base; good for hosting environments. is already
                                                                  .axd

     Steps required                                                mapped to
                                                                     ASP.NET
       Implement the IHttpHandler interface on a class
       Add the handler to web.config file by using an already mapped ASP.NET
        extension


       Client syntax would now refer to the path specified in the web.config
        file in order to invoke the handler
           <a href=“image.axd?id=10”/>
     Examples
       Most common – handler for returning images
       Return JavaScript from a common handler

       Return CSS files from a common handler – allows to compress the CSS
Advanced Asp.Net Concepts And Constructs
Generic Handler

     Similar to the previous approach but uses .ashx as the
      extension
     It’s a convention to use generic handler instead of
      reusing any other ASP.NET extensions
     Steps required
       Implement the IHttpHandler interface on a class
       Add the handler to the web.config file
       Client syntax would be as follows
         Mycustomhandler.ashx?querystring
Advanced Asp.Net Concepts And Constructs
Problem

     ASP.NET processes files that live in the file system.
     Adds a dependency! Not good.
    Solution

     Need to abstract away the details of where the pages
      would be stored and retrieved
     Opens up options for storing web site (and related
      resources) anywhere we want!
VirtualPathProvider to the rescue

       New concept in ASP.NET 2.0
       Extend a few base classes and override some methods
       Part of System.Web.Hosting namespace
       Supports
           ASP.NET Pages (including master pages)
           User controls
           Standard web pages (e.g .htm) and images (e.g. .jpg)
           Themes in the App_Theme folder
     Does not support
           The Global.asax file
           Web.config files
           Site map data used by the XmlSiteMapProvider
           Directories that contain assemblies or generate assemblies: bin,
            App_Code, App_GlobalResources, any App_LocalResources
Implement a custom VirtualPathProvider

     Derive a class from System.Web.Hosting.VirtualPathProvider
     Must override the following methods
        FileExists
            public override bool FileExists(string virtualPath)
        GetFile
            public override VirtualFile GetFile(string virtualPath)
     Must override the following methods (if the provider supports directories) – must
      support directories if supporting Themes
        DirectoryExists
            public override bool DirectoryExists(string virtualDir)
        GetDirectory
            public override VirtualDirectory GetDirectory(string virtualDir)
     Need to derive classes that derive from the following
        VirtualFile
        VirtualDirectory
     What about the file change notifications?
        Easy with the file system based providers (can use FileSystemWatcher class for that
         purpose). What do to in extensible cases where provider knows where the files are stored?
        Need to implement one of the following methods
            GetCacheDependency
            GetFileHash
Register with ASP.NET

     Must be registered with ASP.NET compilation system
      before any page parsing or compilation occurs.
     Normally registered in the Application_Start event in
      the global.asax file



     Or can also be registered in the static AppInitialize
      method in a public class that lives in the App_Code
      folder.
Examples

     WSS/SharePoint use this concept –
      SPVirtualPathProvider. The pages live in the
      WSS/SharePoint content database that ASP.NET has
      no knowledge about.
     Serve web site out of a zip file!
      http://msdn.microsoft.com/en-us/library/aa479502.aspx
     Serve master page from a DLL
      http://blogs.msdn.com/shahpiyush/archive/2007/03/09/S
       haring-Master-Pages-amongst-Applications-by-
       Embedding-it-in-a-Dll_2E00_.aspx
Problem

     We all hate the cryptic URLs visible in the browser
      window?
     What if we could reformat the above URL to look like
      as follows?
    Solution

     Let the user go to the friendly URL (2nd URL above)
     Intercept the incoming request and redirect (on the
      server) it to the actual URL (1st URL above)
     Http Modules to rescue!
Advanced Asp.Net Concepts And Constructs
Response Filter is just that – an object that filters

    the final response before it is sent to the client –
    note that everything else has already run before
    the filter is invoked.
    Anything written to the HttpResponse.Write

    method will eventually go through the installed
    filter.
    The response filter must be a Stream object.


    Added to the Response.Filter property

Examples

     Compress the final output before it is sent to the client
     Search pages where some of the text need to be
      highlighted.
     Returning formatted code files (C#, VB.NET, etc) from
      the server.
     Remove white spaces from the final output
     Make sure that the HTML output is XHTML compliant
       http://aspnetresources.com/articles/HttpFilters.aspx
Advanced Asp.Net Concepts And Constructs
Gotcha

     Filters are not called if the code calls
      HttpApplication.CompleteRequest
     Avoid the following methods b/c they all call
      HttpApplication.CompleteRequest!
       Server.Transfer
       Response.End
       Response.Redirect
     Do use Server.Execute
Used for editing the configuration files @ design

    time or runtime.
    WebConfigurationManager class

     Preferred for web applications (Use
      ConfigurationManager class for Windows applications)
     Supports changes to configuration @ design time
     Use one of the Open methods to get the
      Configuration object (examples on next slide)
Configuration Class

     Represents a configuration file applicable to a particular computer, application or
      resource.

    // Open current application’s (~) web.config file. Pass null for machine level web.config
    // Pass “/” for root web site’s web.config
    Configuration webConfig =
        WebConfigurationManager.OpenWebConfiguration(quot;~quot;);

    // Open local machine.config file
    Configuration machineConfig =
        WebConfigurationManager.OpenMachineConfiguration();

     Use GetSection or GetSectionGroup methods for getting access to the configuration
      sections or configuration section groups.
    ConfigurationSection class

     Returned by the methods of the Configuration and WebConfigurationManager classes.
     Cast to the strongly typed objects: HttpModulesSection, HttpHandlersSection,
      AuthenticationSection, CacheSection, PagesSection, CompilationSection, etc.
     Not all sections can be changed; some are hidden @ run time.
 Code Example – Set authentication to Forms
Configuration webConfig =
  WebConfigurationManager.OpenWebConfiguration(quot;~quot;);
ConfigurationSection configSection =
  webconfig.GetSection(quot;system.web/authenticationquot;);
AuthenticationSection authSection = configSection as
  AuthenticationSection;                        Provided by .NET
if (authSection != null)                        for manipulating
                                               config file sections

{
  authSection.Mode = AuthenticationMode.Forms;
  webconfig.Save();
}                                                   Update the
                                                           <authentication>
                                 Write changes to
                                                            mode to Forms!
                                the web.config file
Advanced Asp.Net Concepts And Constructs
Issues

     Permissions
       Need to have appropriate permissions in order to read
        from or write to the config file(s).
       Need Read permission on the parent config files.
     Application Domain Restarts
       Whenever a setting is changed in the web.config file
                  May use external configuration files to avoid restarting the
                   application domain for certain sections (configSource
                   attribute)
                 
Whether or not to
 restart the app
 domain on the 
  change of the

                 
   external file
Advanced Asp.Net Concepts And Constructs

More Related Content

Advanced Asp.Net Concepts And Constructs

  • 2. IIS and ASP.NET Integration – Deep Dive  HTTP Modules  HTTP Handlers  Virtual Path Provider  URL Rewriting  Response Filters  Configuration Runtime API 
  • 3. Extending web servers by means of installing  some components  Internet Server API – ISAPI (Microsoft)  Netscape Server API – NSAPI (Netscape) IIS is an ISAPI compliant web server   Extension possible through ISAPI Filters and Extensions (both are Win 32 DLLs) Application Mapping in IIS maps the request to  an ISAPI Extension by mapping the request extension to a Win 32 DLL.
  • 4. The integration b/w IIS and ASP.NET occurs through the  Application Mapping – ASP.NET is an ISAPI Extension!
  • 5. IIS   Receives the request  Authenticates the request and attaches a security token (identity) to it.  For authenticated requests, it is the Windows identity of the user connecting to IIS (e.g. Domainusername)  For anonymous requests, it is your old friend IUSR_Machinename or whatever account is specified in IIS for anonymous requests.  Forwards the request along with the token to aspnet_isapi.dll
  • 6. aspnet_isapi.dll   Since it’s a DLL, it will be mapped into the address space of the web server process which runs under the SYSTEM account! Not good!  That’s why it does not do much in terms of processing the request.  Forwards the request to the ASP.NET Worker Process.
  • 7. Worker Process   Provides housing for the worker threads  Aspnet_wp.exe  IIS 5.0 and IIS 5.1  The process identity is determined by the <processModel> node in the machine.config file  W3wp.exe  IIS 6.0 – Worker Process Isolation Mode  The process identity is not determined by the <processModel> node; in-fact almost all of the settings defined by this node are ignored.  The process identity is determined by the Application Pool identity.  IIS 6.0 – IIS 5 Isolation Mode  Works like IIS 5
  • 8. Identities   Process Identity – discussed earlier  Worker Thread Identity!  Why is it needed?  To answer that, think about what would happen if there is no thread identity?  What could be the thread identity?  The thread identity could be one of the following:  Identity of the Worker Process.  Identity passed by IIS to ASP.NET.  Identity specified in the <identity> node in the web.config.
  • 9. Identities   Thread Identity  How is it determined which identity out of the three will be used?  Identity of the Worker Process  Impersonation is disabled <identity impersonate=“false”/> (the default setting)  Identity passed by IIS  Impersonation is enabled <identity impersonate=“true”/>  Identity specified in the <identity> node in the web.config  Impersonation is enabled and a specific identity has been specified in the web.config file <identity impersonate=“true” userName=“manny” password=“mannypwd”/>
  • 10. A class that participates in the ASP.NET request  processing pipe-line (by virtue of registering for the events) Provides high level of componentization  ASP.NET implements some of its functionalities  using HTTP modules
  • 11. Implements the IHttpModule interface 
  • 12. Configure the module using web.config file  ASP.NET Modules 
  • 14. Tips/Tricks   Modules are called for each and every request which is handled by ASP.NET for that application; no configuration to run the HTTP module for selective requests  Write custom if-then-else checks in the module code.  The events raised by HTTP modules and the HttpApplication class are captured in the Global.asax  Convention: ModuleName_EventName  Examples: Session_Start, Session_End, CustomModule_MyCustomEvent  That means the custom modules can also raise events and those events can be captured in the Global.asax file!
  • 15. Tips/Tricks   Did you know that the events raised by modules can also be captured by other modules? How to do that? HttpApplication maintains the modules collection Module name from the config file Event raised by the Session module
  • 16. Tips/Tricks   HTTP modules are called in the order in which the modules have been defined in the web.config file.  For example, WSS SharePoint hijacks the ASP.NET pipe- line by clearing all of the existing modules and installing a custom module as the very first module! WSS/MOSS module installed as the 1st module in the ASP.NET page processing pipeline
  • 17. Tips/Tricks   ASP.NET framework changes its behavior slightly for the .asmx requests, which in turn affects the way HTTP modules behave.  Unhandled exception in an ASP.NET web page or an HttpHandler raises the Error event as usual.  Unhandled exception in an ASMX web service gets translated into a SOAP Fault! You would have to write SOAP Extension to deal with it.
  • 18. Practical uses for HTTP modules   Application wide exception handling
  • 19. Practical uses for HTTP modules   Referrer tracking
  • 20. Practical uses for HTTP modules   URL Rewriting
  • 21. Practical use of HTTP modules   Security  Force the user to change password @ the time of first login.  Force the user to accept the terms and conditions
  • 22. A class that is the final destination for a request  that comes to ASP.NET Must implement the IHttpHandler interface  ASP.NET uses handlers for implementing most of  its functionality
  • 23. Use the <httpHandlers> node to register any  handlers There are three ways of using a handler   For processing a custom request (e.g. handler for processing .rdnug files)  For processing requests to an already mapped ASP.NET extension (e.g. image.axd)  Similar to the 2nd option – Directly calling a handler without using any custom or commonly used ASP.NET extensions – generic handler!
  • 24. Processing a custom request   Allows you to define your own custom extension  Requires changes to IIS! Not good for hosted applications.  Steps required  Implement the IHttpHandler interface on a class  Add a new Application Mapping for the new extension in order for the requests to be re-reroute to ASP.NET  Add the handler to the web.config file  Client syntax would be as follows  http://site/virtualdirectory/test.rdnug
  • 26. Process an already mapped extension   Allow you to re-use an already mapped ASP.NET extension  No changes to the IIS meta-base; good for hosting environments. is already .axd  Steps required mapped to ASP.NET  Implement the IHttpHandler interface on a class  Add the handler to web.config file by using an already mapped ASP.NET extension  Client syntax would now refer to the path specified in the web.config file in order to invoke the handler  <a href=“image.axd?id=10”/>  Examples  Most common – handler for returning images  Return JavaScript from a common handler  Return CSS files from a common handler – allows to compress the CSS
  • 28. Generic Handler   Similar to the previous approach but uses .ashx as the extension  It’s a convention to use generic handler instead of reusing any other ASP.NET extensions  Steps required  Implement the IHttpHandler interface on a class  Add the handler to the web.config file  Client syntax would be as follows  Mycustomhandler.ashx?querystring
  • 30. Problem   ASP.NET processes files that live in the file system.  Adds a dependency! Not good. Solution   Need to abstract away the details of where the pages would be stored and retrieved  Opens up options for storing web site (and related resources) anywhere we want!
  • 31. VirtualPathProvider to the rescue   New concept in ASP.NET 2.0  Extend a few base classes and override some methods  Part of System.Web.Hosting namespace  Supports  ASP.NET Pages (including master pages)  User controls  Standard web pages (e.g .htm) and images (e.g. .jpg)  Themes in the App_Theme folder  Does not support  The Global.asax file  Web.config files  Site map data used by the XmlSiteMapProvider  Directories that contain assemblies or generate assemblies: bin, App_Code, App_GlobalResources, any App_LocalResources
  • 32. Implement a custom VirtualPathProvider   Derive a class from System.Web.Hosting.VirtualPathProvider  Must override the following methods  FileExists  public override bool FileExists(string virtualPath)  GetFile  public override VirtualFile GetFile(string virtualPath)  Must override the following methods (if the provider supports directories) – must support directories if supporting Themes  DirectoryExists  public override bool DirectoryExists(string virtualDir)  GetDirectory  public override VirtualDirectory GetDirectory(string virtualDir)  Need to derive classes that derive from the following  VirtualFile  VirtualDirectory  What about the file change notifications?  Easy with the file system based providers (can use FileSystemWatcher class for that purpose). What do to in extensible cases where provider knows where the files are stored?  Need to implement one of the following methods  GetCacheDependency  GetFileHash
  • 33. Register with ASP.NET   Must be registered with ASP.NET compilation system before any page parsing or compilation occurs.  Normally registered in the Application_Start event in the global.asax file  Or can also be registered in the static AppInitialize method in a public class that lives in the App_Code folder.
  • 34. Examples   WSS/SharePoint use this concept – SPVirtualPathProvider. The pages live in the WSS/SharePoint content database that ASP.NET has no knowledge about.  Serve web site out of a zip file!  http://msdn.microsoft.com/en-us/library/aa479502.aspx  Serve master page from a DLL  http://blogs.msdn.com/shahpiyush/archive/2007/03/09/S haring-Master-Pages-amongst-Applications-by- Embedding-it-in-a-Dll_2E00_.aspx
  • 35. Problem   We all hate the cryptic URLs visible in the browser window?  What if we could reformat the above URL to look like as follows? Solution   Let the user go to the friendly URL (2nd URL above)  Intercept the incoming request and redirect (on the server) it to the actual URL (1st URL above)  Http Modules to rescue!
  • 37. Response Filter is just that – an object that filters  the final response before it is sent to the client – note that everything else has already run before the filter is invoked. Anything written to the HttpResponse.Write  method will eventually go through the installed filter. The response filter must be a Stream object.  Added to the Response.Filter property 
  • 38. Examples   Compress the final output before it is sent to the client  Search pages where some of the text need to be highlighted.  Returning formatted code files (C#, VB.NET, etc) from the server.  Remove white spaces from the final output  Make sure that the HTML output is XHTML compliant  http://aspnetresources.com/articles/HttpFilters.aspx
  • 40. Gotcha   Filters are not called if the code calls HttpApplication.CompleteRequest  Avoid the following methods b/c they all call HttpApplication.CompleteRequest!  Server.Transfer  Response.End  Response.Redirect  Do use Server.Execute
  • 41. Used for editing the configuration files @ design  time or runtime. WebConfigurationManager class   Preferred for web applications (Use ConfigurationManager class for Windows applications)  Supports changes to configuration @ design time  Use one of the Open methods to get the Configuration object (examples on next slide)
  • 42. Configuration Class   Represents a configuration file applicable to a particular computer, application or resource. // Open current application’s (~) web.config file. Pass null for machine level web.config // Pass “/” for root web site’s web.config Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(quot;~quot;); // Open local machine.config file Configuration machineConfig = WebConfigurationManager.OpenMachineConfiguration();  Use GetSection or GetSectionGroup methods for getting access to the configuration sections or configuration section groups. ConfigurationSection class   Returned by the methods of the Configuration and WebConfigurationManager classes.  Cast to the strongly typed objects: HttpModulesSection, HttpHandlersSection, AuthenticationSection, CacheSection, PagesSection, CompilationSection, etc.  Not all sections can be changed; some are hidden @ run time.
  • 43.  Code Example – Set authentication to Forms Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(quot;~quot;); ConfigurationSection configSection = webconfig.GetSection(quot;system.web/authenticationquot;); AuthenticationSection authSection = configSection as AuthenticationSection; Provided by .NET if (authSection != null) for manipulating config file sections { authSection.Mode = AuthenticationMode.Forms; webconfig.Save(); } Update the <authentication> Write changes to mode to Forms! the web.config file
  • 45. Issues   Permissions  Need to have appropriate permissions in order to read from or write to the config file(s).  Need Read permission on the parent config files.  Application Domain Restarts  Whenever a setting is changed in the web.config file  May use external configuration files to avoid restarting the application domain for certain sections (configSource attribute)  Whether or not to restart the app domain on the  change of the  external file