Custom #HttpModule to respond to every #HTTP request.
Let’s say you wanted to create a HTTP endpoint that could respond with data that is completely generated from a c# class, and independent of the structure of the Url – for example, if you wanted to create a REST based HTTP API, that could accept a very flexible Url structure.
For example, perhaps a API that allowed it’s users to specify clauses in the URL, like yourapi.com/filter/a=5 or something like that.
Anyway, you create a class that implements IHTTPHandler as follows;
using System;
using System.Web;
public class CacheModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += application_BeginRequest;
}
static void application_BeginRequest(object sender, EventArgs e)
{
var application = (HttpApplication)sender;
var context = application.Context;
context.Response.Write(“<b>Cache Module</b> – Requested url:” + context.Request.Url);
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
public void Dispose() { }
}
Then you need to define this in the web.config;
<?xml version=”1.0″?>
<configuration>
<system.web>
<compilation debug=”true” targetFramework=”4.5″ />
<httpRuntime targetFramework=”4.5″ requestPathInvalidCharacters=”<,>,*,%,&,:,\,?”/>
</system.web>
<system.webServer>
<modules>
<add name=”CacheModule” type=”CacheModule“/>
</modules>
</system.webServer>
</configuration>