共用方式為


Example Configuration Code for an HTTP Module 

This code example demonstrates a Web page that contains code to configure an HTTP module. For details about how to use this page and links to the other files in this example, see How to: Create and Configure an HTTP Module.

Example

The following code example performs these actions:

  • Enumerates the existing HTTP modules that are configured for an ASP.NET application called /Temp.

  • Tests to determine whether there is an existing configuration setting for the HTTP module called RequestTimeIntervalModule. To examine the code for this module, see Example HTTP Module.

  • Provides the option to remove any existing settings.

  • Creates a setting, if it does not already exist, for the HTTP module called RequestTimeIntervalModule.

An HttpModuleAction object is created for the new RequestTimeIntervalModul``e HTTP module. This object is first used to search for an existing configuration setting, and then used to add a new configuration setting. The format of the constructor's second parameter is type name[, assembly name]. You need to include the assembly name if you have compiled the HTTP module into a DLL file and placed it in the Bin folder of the ASP.NET application. You do not need to include the assembly name if you have placed the source-code file for the HTTP module in the App_Code folder of the ASP.NET application.

This code can also be run from an .aspx page if the proper alterations are made and the user has Read and Write permissions for the Web.config file. Typically, these permissions are restricted to the server administrator.

Imports System.Configuration
Imports System.Web.Configuration
Imports System.Text

Namespace Samples.Aspnet.Configure
  Class ConfigureHttpModule
    Sub Main()

        Try
            ' Set the configPath value to the path for your target Web site.
            Dim configPath As String = "/Temp"

            ' Get the configuration object.
            Dim config As Configuration = _
                WebConfigurationManager.OpenWebConfiguration(configPath)

            ' Call the EnumerateHttpModules subroutine.
            EnumerateHttpModules(config)

            ' Call ConfigureHttpModules subroutine.
            ConfigureHttpModules(config)

        Catch e As Exception
            Console.WriteLine(e.ToString)
        End Try

    End Sub

    Private Sub ConfigureHttpModules(ByVal config As Configuration)
        Console.WriteLine()

        ' Get the <httpModules> section.
        Dim section As HttpModulesSection = _
            config.GetSection("system.web/httpModules")

        ' Create a new module action object.
        Dim myHttpModuleAction As HttpModuleAction = _
            New HttpModuleAction("RequestTimeIntervalModule", _
            "Samples.Aspnet.HttpModuleExamples.RequestTimeIntervalModule")

        ' Look for an existing configuration for this module.
        Dim indexOfModule As Integer = section.Modules.IndexOf(myHttpModuleAction)
        If Not (-1 = indexOfModule) Then
            Console.WriteLine("RequestTimeIntervalModule module is already configured at index {0}", _
                indexOfModule)
            Console.WriteLine("Delete existing module configuration? (Y/N)")
            Dim deleteModule As String = Console.ReadLine()
            If (("Y" = deleteModule) Or ("y" = deleteModule)) Then
                section.Modules.Remove("RequestTimeIntervalModule")
                If Not (section.SectionInformation.IsLocked) Then
                    config.Save()
                End If
                Console.WriteLine("Existing RequestTimeIntervalModule module configuration deleted.")
                Console.WriteLine("Run the tool again to configure the RequestTimeIntervalModule module.")
            Else
                Console.WriteLine("Configuration not changed")
            End If
        Else
            section.Modules.Add(myHttpModuleAction)

            If Not (section.SectionInformation.IsLocked) Then
                config.Save()
                Console.WriteLine("RequestTimeIntervalModule module configured.")
            Else
                Console.WriteLine("Could not configure RequestTimeIntervalModule module.")
            End If
        End If
    End Sub

    Private Sub EnumerateHttpModules(ByVal config As Configuration)
        Console.WriteLine()

        ' Get the <httpModules> section.
        Dim section As HttpModulesSection = _
            config.GetSection("system.web/httpModules")

        Dim output As StringBuilder = New StringBuilder()
        output.AppendFormat("<httpModules> element in {0}:", _
            config.FilePath.ToString())
        output.AppendLine()

        Dim i As Integer
        For i = 0 To (section.Modules.Count - 1)
            output.AppendFormat("  {0}, {1}", _
                section.Modules(i).Name.ToString(), _
                section.Modules(i).Type.ToString())
            output.AppendLine()
        Next i

        Console.WriteLine(output)
    End Sub
  End Class
End Namespace
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web.Configuration;

namespace Samples.Aspnet.Configure
{
    class ConfigureHttpModule
    {
        static void Main(string[] args)
        {
            try
            {
                // Set the configPath value to the path for your target Web site.
                string configPath = "/Temp";

                // Get the configuration object.
                Configuration config =
                  WebConfigurationManager.OpenWebConfiguration(configPath);

                // Call the EnumerateHttpModules subroutine.
                EnumerateHttpModules(config);

                // Call ConfigureHttpModules subroutine.
                ConfigureHttpModules(config);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void ConfigureHttpModules(Configuration config)
        {
            Console.WriteLine();

            // Get the <httpModules> section.
            HttpModulesSection section = 
                (HttpModulesSection)config.GetSection("system.web/httpModules");

            // Create a new module action object.
            HttpModuleAction myHttpModuleAction = new HttpModuleAction(
                "RequestTimeIntervalModule",
                "Samples.Aspnet.HttpModuleExamples.RequestTimeIntervalModule");
            
            // Look for an existing configuration for this module.
            int indexOfModule = section.Modules.IndexOf(myHttpModuleAction);
            if (-1 != indexOfModule)
            {
                Console.WriteLine("RequestTimeIntervalModule module is already configured at index {0}",
                    indexOfModule);
                Console.WriteLine("Delete existing module configuration? (Y/N)");
                string deleteModule = Console.ReadLine();
                if (("Y" == deleteModule) || ("y" == deleteModule))
                {
                    section.Modules.Remove("RequestTimeIntervalModule");
                    if (!section.SectionInformation.IsLocked)
                        config.Save();

                    Console.WriteLine("Existing RequestTimeIntervalModule module configuration deleted.");
                    Console.WriteLine("Run the tool again to configure the RequestTimeIntervalModule module.");
                }
                else
                {
                    Console.WriteLine("Configuration not changed");
                }
            }
            else
            {
                section.Modules.Add(myHttpModuleAction);

                if (!section.SectionInformation.IsLocked)
                {
                    config.Save();
                    Console.WriteLine("RequestTimeIntervalModule module configured.");
                }
                else
                {
                    Console.WriteLine("Could not configure RequestTimeIntervalModule module.");
                }
            }

        }

        private static void EnumerateHttpModules(Configuration config)
        {
            Console.WriteLine();

            // Get the <httpModules> section.
            HttpModulesSection section = 
                (HttpModulesSection)config.GetSection("system.web/httpModules");

            StringBuilder output = new StringBuilder();
            output.AppendFormat("<httpModules> modules element in {0}:\r\n", 
                config.FilePath.ToString());

            for (int i = 0; i < section.Modules.Count; i++)
            {
                output.AppendFormat("  {0}, {1}\r\n", 
                    section.Modules[i].Name.ToString(), 
                    section.Modules[i].Type.ToString());
            }

            Console.WriteLine(output);

        }
    }
}

See Also

Tasks

How to: Create and Configure an HTTP Module

Reference

httpModules Element (ASP.NET Settings Schema)
HttpModuleAction
HttpModuleActionCollection
HttpModulesSection

Concepts

Example HTTP Module

Other Resources

Extending ASP.NET Processing with HTTP Modules