ASP.NET Tutorial/Development/HTTP Modules — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 11:56, 26 мая 2010

Adding the HttpHandler configuration information to web.config

using System;
using System.Web;
public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/jpeg";
        context.Response.WriteFile("Sunset.jpg");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}


Creating Custom HTTP Modules

An HTTP Module is a .NET class that executes with each and every page request. 
The HTTP Module doesn"t allow you to request a page unless you include the proper query string with the request. 
File: App_Code\QueryStringAuthenticationModule.cs
using System;
using System.Web;
namespace MyNamespace
{
    public class QueryStringAuthenticationModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            app.AuthorizeRequest += new EventHandler(AuthorizeRequest);
        }
        private void AuthorizeRequest(Object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;
            string path = context.Request.AppRelativeCurrentExecutionFilePath;
            if (String.rupare(path, "~/login.aspx", true) == 0)
                return;
            bool authenticated = false;
            if (context.Request.QueryString["password"] != null)
            {
                if (context.Request.QueryString["password"] == "secret")
                    authenticated = true;
            }
            if (!authenticated)
                context.Response.Redirect("~/Login.aspx");
        }
        public void Dispose() { }
    }
}
            
Register the HTTP Module in the web configuration file. 
File: Web.Config
<configuration>
    <system.web>
      <httpModules>
        <add name="QueryStringAuthenticationModule"
             type="MyNamespace.QueryStringAuthenticationModule"/>
      </httpModules>
    </system.web>
</configuration>


HttpContext (C#)

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
namespace Demo
{
    public class AppendMessage : IHttpModule
    {
        private HttpContext _current = null;
        #region IHttpModule Members
        public void Dispose()
        {
            throw new Exception("The method or operation is not implemented.");
        }
        public void Init(System.Web.HttpApplication context)
        {
            _current = context.Context;
            context.PreSendRequestContent +=
                new EventHandler(context_PreSendRequestContent);
        }
        void context_PreSendRequestContent(object sender, EventArgs e)
        {
            string message = "<!-- This page has been post processed at " +
                             System.DateTime.Now.ToString() +
                             " by a custom HttpModule.-->";
            _current.Response.Output.Write(message);
        }
        #endregion
    }
}
File: Web.config

 
<configuration>
    <system.web>
      <httpModules>
        <add name="AppendMessage" type="AppendMessage, App_code" />
      </httpModules>
    </system.web>
</configuration>


HttpContext (VB)

Imports Microsoft.VisualBasic
Imports System.Web
Public Class AppendMessage
    Implements IHttpModule
    Dim WithEvents _application As HttpApplication = Nothing
    Public Overridable Sub Init(ByVal context As HttpApplication) _
            Implements IHttpModule.Init
        _application = context
    End Sub
    Public Overridable Sub Dispose() Implements IHttpModule.Dispose
    End Sub
    Public Sub context_PreSendRequestContent(ByVal sender As Object, _
            ByVal e As EventArgs) Handles _application.PreSendRequestContent
        Dim message As String = "<!-- This page has been post processed at " & _
                                System.DateTime.Now.ToString() & _
                                " by a custom HttpModule.-->"
        _application.Context.Response.Output.Write(message)
    End Sub
End Class
File: Web.config
 
<configuration>
    <system.web>
      <httpModules>
        <add name="AppendMessage" type="AppendMessage, App_code" />
      </httpModules>
    </system.web>
</configuration>


HttpModule Tester

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="HttpModuleTester" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>HttpModuleTester</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class HttpModuleTester : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext myHttpContext = HttpContext.Current;
        HttpApplication myHttpApplication = myHttpContext.ApplicationInstance;
        HttpModuleCollection myHttpModuleCollection = myHttpApplication.Modules;
        for (int index=0; index < myHttpModuleCollection.Count; index++)
        {
            IHttpModule module = myHttpModuleCollection.Get(index);
            Response.Write("Module = " + module.ToString() + "<br>");
        }
        string httpModuleName = myHttpModuleCollection.GetKey(1);
        Response.Write("The name of the HttpModule object at index 1" + " is " + """ + httpModuleName + ""." + "<br><br>");
        string[] allModules = myHttpModuleCollection.AllKeys;
        Response.Write("<b>The HttpModule objects contained in the HttpModuleCollection are:</b><br>");
        for (int i = 0; i < allModules.Length; i++)
            Response.Write("Module " + i + "  : " + allModules[i] + "<br>");
    }
}


Outputting an image from an HttpHandler (C#)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>HttpHandler Serving an Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <img src="ImageHandler.ashx" />
    </div>
    </form>
</body>
</html>
File: Handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/jpeg"
        context.Response.WriteFile("Sunset.jpg")
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}


Outputting an image from an HttpHandler (VB)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>HttpHandler Serving an Image</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <img src="ImageHandler.ashx" />
    </div>
    </form>
</body>
</html>
File: Handler.ashx
<%@ WebHandler Language="VB" Class="Handler" %>
Imports System
Imports System.Web
Public Class Handler : Implements IHttpHandler
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        context.Response.ContentType = "image/jpeg"
        context.Response.WriteFile("Sunset.jpg")
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class


The IHttpHandler page template (C#)

File: Handler.ashx
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}


The IHttpHandler page template (VB)

File: Handler.ashx
<%@ WebHandler Language="VB" Class="Handler" %>
Imports System
Imports System.Web
Public Class Handler : Implements IHttpHandler
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        context.Response.ContentType = "text/plain"
        context.Response.Write("Hello World")
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class


URL rewriting HttpModule (C#)

using System.Web;
public class SimpleRewriter : System.Web.IHttpModule
{
    HttpApplication _application = null;
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new System.EventHandler(context_BeginRequest);
        _application = context;
    }
    public void Dispose()
    {
    }
    private void context_BeginRequest(object sender, System.EventArgs e)
    {
        string requesturl =
            _application.Context.Request.Path.Substring(0,
                _application.Context.Request.Path.LastIndexOf("//")
            );
        string[] parameters = requesturl.Split(new char[] { "/" });
        if (parameters.Length > 1)
        {
            string firstname = parameters[1];
            string lastname = parameters[2];
            _application.Context.RewritePath("~/unfriendly.aspx?firstname=" +
                firstname + "&lastname=" + lastname);
        }
    }
}


URL rewriting HttpModule (VB)

Imports Microsoft.VisualBasic
Imports System.Web
Public Class SimpleRewriter
    Implements System.Web.IHttpModule
    Dim WithEvents _application As HttpApplication = Nothing
    Public Overridable Sub Init(ByVal context As HttpApplication) _
            Implements IHttpModule.Init
        _application = context
    End Sub
    Public Overridable Sub Dispose() Implements IHttpModule.Dispose
    End Sub
    Public Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) _
            Handles _application.BeginRequest
        Dim requesturl As String = _
            _application.Context.Request.Path.Substring(0, _
            _application.Context.Request.Path.LastIndexOf("/"c))
        Dim parameters() As String = _
            requesturl.Split(New [Char]() {"/"c}, _
                StringSplitOptions.RemoveEmptyEntries)
        If (parameters.Length > 1) Then
            Dim firstname As String = parameters(1)
            Dim lastname As String = parameters(2)
            _application.Context.RewritePath("~/unfriendly.aspx?firstname=" & _
                firstname & "&lastname=" & lastname)
        End If
    End Sub
End Class