Home > Uncategorized > Custom #HttpModule to respond to every #HTTP request.

Custom #HttpModule to respond to every #HTTP request.

356030_0209_4

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=”&lt;,&gt;,*,%,&amp;,:,\,?”/>
</system.web>
<system.webServer>
<modules>
<add name=”CacheModule” type=”CacheModule“/>
</modules>
</system.webServer>
</configuration>

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: