This sample can be used to block a particular IP address from accessing resources on your website.We can retrieve information regarding client browser and client machine by making use of the Request object.Asp.Net uses a series of modules to get the work done for you.For a list of available modules in ASP.Net you can refer machine.config file present in %windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG folder.You can either use these modules or can create your custom module for the same.
Terms Used:-
HttpModule:-
An HttpModule is an assembly that implements the IHttpModule interface and handles events. ASP.NET includes a set of HttpModules that can be used by your application. For example, the SessionStateModule is provided by ASP.NET to supply session state services to an application. Custom HttpModules can be created to respond to either ASP.NET events or user events.
The general process for writing an HttpModule is:
Implement the IHttpModule interface. Handle the Init method and register for the events you need. Handle the events. Optionally implement the Dispose method if you have to do cleanup. Register the module in Web.config.
HttpContext:-
Encapsulates all HTTP-specific information about an individual HTTP request.
Namespace: System.Web Assembly: System.Web (in System.Web.dll)
Classes that inherit the IHttpModule and IHttpHandler interfaces are provided a reference to an HttpContext object for the current HTTP request. The object provides access to the intrinsic Request, Response, and Server properties for the request.
public class SecurityHttpModule:IHttpModule
{
public SecurityHttpModule() { }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Application_BeginRequest);
}
private void Application_BeginRequest(object source, EventArgs e)
{
HttpContext context = ((HttpApplication)source).Context;
string ipAddress = context.Request.UserHostAddress;
if (!IsValidIpAddress(ipAddress))
{
context.Response.StatusCode = 403; // (Forbidden)
}
}
private bool IsValidIpAddress(string ipAddress)
{
return (ipAddress == "127.0.0.7");
}
public void Dispose() { /* clean up */ }
}
Following entries need to be made in the config file.
type="SecurityHttpModule, SecurityHttpModule " />
|
| Author: Mahesh Raj 07 Jun 2008 | Member Level: Gold Points : 1 |
This is very good information,Continue posting such useful articles.
|
| Author: Rakesh Kumar 08 Jun 2008 | Member Level: Bronze Points : 1 |
Excellent Article Sir I want to know more about http handlers , their benefits etc.
|