HTTP Modules
Every now and then, you will have some difficult task for which even SOAP extensions won't work. For example, you may need to filter out SOAP requests that don't have a UserAgent that is set to "My OK UserAgent".
HTTP modules are the way to do this. They allow you as a developer to intercept every request that comes into ASP.NET, at several various events, such as when the request begins, or when an error occurs. They are similar to ISAPI filters. If a SOAP extension is the wrong place to do something, then you certainly can do it with a module.
Let's write a short sample module that will send a SOAP fault for any requests that don't include the right user-agent in the HTTP headers. In this case, the user-agent must be "Cool UserAgent". To begin, we will need to import the System and System.Web namespace, and make sure that our class implements the IHttpModule interface:
using System;
using System.Web;
namespace WhatMyName
{
public class CheckUserAgentModule : IHttpModule
Next, we'll need to implement the Init function, which will hand us the HttpApplication object for the entire ASP.NET application. We can use this object to register for the OnRequest event:
public void Init( HttpApplication context )
{
context.BeginRequest += new EventHandler(
CheckUserAgentModule_BeginRequest );
return;
}
Now, we need to implement the CheckUserAgentModule_Begin Request method:
public void CheckUserAgentModule_BeginRequest( Object o, EventArgs e )
{
String userAgent =
((HttpApplication)o).Request.UserAgent;
if( userAgent != "Cool UserAgent" )
{
String err =
@"<soap:Envelope
xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>";
err +=
"User-Agent \"" + userAgent + "\" not allowed"; err += @"</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>";
((HttpApplication)o).Response.ContentType = "text/xml";
((HttpApplication)o).Response.Write( err );
((HttpApplication)o).CompleteRequest();
}
}
Notice that we call the CompleteRequest method at the end. This does two things: It closes up the request stream, and it stops any other modules from running. The last step is to register the module in web.config (or machine.config if we want it registered for the entire system).
<httpModules>
<add name="UserAgentCheck" type="WhatMyName.CheckUserAgentModule, WhatMyName" />
</httpModules>
Although developing modules is generally very easy, think of modules as a last resort. Modules offer no specific SOAP support; therefore, you will lose all of the nice SOAP-based features that the .NET framework offers. Furthermore, you will sacrifice the advantage of the interoperability work and testing that Microsoft has done to ensure that the SOAP support in the .NET Framework is compliant with the SOAP specification.
|