What is HTTP handler: Every request into an ASP.NET application is handled by a specialized component known as an HTTP handler. The HTTP handler is the most important ingredient while handling ASP.NET requests.
HttpHanlder is the low level Request and Response API to service incoming Http requests. All handlers implement the IHttpHandler interface. There is no need to use any extra namespace to use it as it contains in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.
Each incoming HTTP request received by ASP.NET is ultimately processed by a specific instance of a class that implements IHTTPHanlder. IHttpHanlderFactory provides the infrastructure that handles the actual resolution of URL requests to IHttpHanlder instances. In addition to the default IHttpHandlerFactory classes provided by ASP.NET, developers can optionally create and register factories to support rich request resolution.
Examples: ASP.NET uses different HTTP handlers to serve different file types. For example, the handler for web Page creates the page and control objects, runs your code, and renders the final HTML.
ASP.NET default handlers:
Examples:
Where HTTP handlers are defined: All HTTP handlers are defined in the <httpHandlers> section of a configuration file which is nested in the <system.web> element.
<httpHandlers>
<add verb="*" path="trace.axd" validate="true" type="System.Web.Handlers.TraceHandler"/>
<add verb="*" path="*.config" validate="true" type="System.Web.HttpForbiddenHandler"/>
<add verb="*" path="*.cs" validate="true" type="System.Web.HttpForbiddenHandler"/>
<add verb="*" path="*.aspx" validate="true" type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>

Use of HTTP Modules:
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
<add name="WindowsAuthentication"
type="System.Web.Security.WindowsAuthenticationModule"/>
<add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule"/>
</httpModules>
Note:
Step 1: What all we need to know before writing handlers
There are two type of handler you actually can make
Step 3: Add a class and name it "SimpleHandler"
Step 4: Write below code

Here we are implementing IHttpHandler
Full code look like below
public class SimpleHandler : IHttpHandler { #region IHttpHandler Members
HttpHanlder is the low level Request and Response API to service incoming Http requests. All handlers implement the IHttpHandler interface. There is no need to use any extra namespace to use it as it contains in the System.Web namespace. Handlers are somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.
Each incoming HTTP request received by ASP.NET is ultimately processed by a specific instance of a class that implements IHTTPHanlder. IHttpHanlderFactory provides the infrastructure that handles the actual resolution of URL requests to IHttpHanlder instances. In addition to the default IHttpHandlerFactory classes provided by ASP.NET, developers can optionally create and register factories to support rich request resolution.
Examples: ASP.NET uses different HTTP handlers to serve different file types. For example, the handler for web Page creates the page and control objects, runs your code, and renders the final HTML.
ASP.NET default handlers:
- Page Handler (.aspx) - Handles Web pages
- User Control Handler (.ascx) - Handles Web user control pages
- Web Service Handler (.asmx) - Handles Web service pages
- Trace Handler (trace.axd) - Handles trace functionality
Examples:
- Dynamic image creator - Use the System.Drawing classes to draw and size your own images.
- RSS - Create a handler that responds with RSS-formatted XML. This would allow you to add RSS feed capabilities to your sites.
- Render a custom image,
- Perform an ad hoc database query,
- Return some binary data.
Where HTTP handlers are defined: All HTTP handlers are defined in the <httpHandlers> section of a configuration file which is nested in the <system.web> element.
<httpHandlers>
<add verb="*" path="trace.axd" validate="true" type="System.Web.Handlers.TraceHandler"/>
<add verb="*" path="*.config" validate="true" type="System.Web.HttpForbiddenHandler"/>
<add verb="*" path="*.cs" validate="true" type="System.Web.HttpForbiddenHandler"/>
<add verb="*" path="*.aspx" validate="true" type="System.Web.UI.PageHandlerFactory"/>
</httpHandlers>
- Trace.axd : this handler is meant for rendering HTML page with a list of all the recently collected trace output, and this is handled by TraceHandler
- .config: Handled by HttpForbiddenHandler
- .cs: Handled by HttpForbiddenHandler
- .aspx: Handled by PageHandlerFactory, which isn't a HTTP handler rather it's a class that will create the appropriate HTTP handler.
Use of HTTP Modules:
- ASP.NET uses HTTP modules to enable features like caching, authentication, error pages etc.
- <add> and <remove> tags can be used to add and inactive any http module from <httpmodule> section of a configuration file.
<add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/>
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
<add name="WindowsAuthentication"
type="System.Web.Security.WindowsAuthenticationModule"/>
<add name="FormsAuthentication"
type="System.Web.Security.FormsAuthenticationModule"/>
</httpModules>
Note:
- HTTP handler plays same role what ISAPI extension
- HTTP module plays same role what ISAPI filters does.
Step 1: What all we need to know before writing handlers
There are two type of handler you actually can make
- Synchronous handler , which implement IHttpHandler interface
- Asynchronous handler, which implement IHttpAsyncHandler. With asynchronous handlers additional requests can be accepted, because the handler creates a new thread to process each request rather than using the worker process
- The ProcessRequest method handles the actual processing for requests made.
ASP.NET calls this method when a request is received. It's where the HTTP handlers perform all the processing. You can access the intrinsic ASP.NET objects (such as Request, Response, and Server) through the HttpContext object that's passed to this method.
- Boolean IsReusable property specifies whether your handler can be pooled for reuse (to increase performance) or whether a new handler is required for each request.
After ProcessRequest() finishes its work, ASP.NET checks this property to determine whether a given instance of an HTTP handler can be reused. If it returns true, the HTTP handler object can be reused for another request of the same type current. If it returns false, the HTTP handler object will simply be discarded.
Step 3: Add a class and name it "SimpleHandler"
Step 4: Write below code
Here we are implementing IHttpHandler
Full code look like below
public class SimpleHandler : IHttpHandler { #region IHttpHandler Members
bool IHttpHandler.IsReusable
{
get { return true; }
}
{
get { return true; }
}
void IHttpHandler.ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
response.Write("<html><body><h1>Wow.. We created our first handler");
response.Write("</h1></body></html>");
}
{
HttpResponse response = context.Response;
response.Write("<html><body><h1>Wow.. We created our first handler");
response.Write("</h1></body></html>");
}
#endregion }
Step 5: Configuring HTTP handler in configuration file;
We will add our handler in <httpHandlers> section
<httpHandlers> <add verb="*" path="vishal.nayan" type="MyHttpHandler.SimpleHandler,MyHttpHandler"/></httpHandlers>
Now here we need to understand what these attributes means
Step 5: Configuring HTTP handler in configuration file;
We will add our handler in <httpHandlers> section
<httpHandlers> <add verb="*" path="vishal.nayan" type="MyHttpHandler.SimpleHandler,MyHttpHandler"/></httpHandlers>
Now here we need to understand what these attributes means
- Verb: indicates whether the request is an HTTP POST or HTTP GET request (use * for all requests).
- Path : indicates the file extension that will invoke the HTTP handler
- Type: identifies the HTTP handler class. This identification consists of two portions. First is the fully qualified class name , That portion is followed by a comma and the name of the DLL assembly that contains the class
Step 6: How to run our Handler
Well, visual studio doesn't allow us directly to run the handler, rather we need to run the project first and then explicitly type URL to request for handler, so in our case it is;
http://localhost:3238/myhttphandler/vishal.nayan

Now, can we create HTTPHanlder without configuring web.config file. Well yes. In visual studio we have a new item template to accomplish this. For this we can use the recognized extension .ashx. All requests that end in .ashx are automatically recognized as requests for a custom HTTP handler.

What is leeching: sites that steal bandwidth by linking to resources on your server .i.e. giving an image URL path from their server to your server, so when user tries to access that image, it's actually using your server resources.
Problem Scenario: As stated above, when any request for image is originated from same website then it's ok, but if the request is coming from another website, then there is a potential problem, as it is creating more work for your web server and reducing the bandwidth.
Solution: HTTP handler will refuse to serve the image or they substitute a dummy image if the referrer header indicates that a request originates from another site.
Add a generic handler from existing item and name it ImageHandler.ashx. Write the code below;
public class ImageHandler : IHttpHandler{
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
Well, visual studio doesn't allow us directly to run the handler, rather we need to run the project first and then explicitly type URL to request for handler, so in our case it is;
http://localhost:3238/myhttphandler/vishal.nayan
Now, can we create HTTPHanlder without configuring web.config file. Well yes. In visual studio we have a new item template to accomplish this. For this we can use the recognized extension .ashx. All requests that end in .ashx are automatically recognized as requests for a custom HTTP handler.
What is leeching: sites that steal bandwidth by linking to resources on your server .i.e. giving an image URL path from their server to your server, so when user tries to access that image, it's actually using your server resources.
Problem Scenario: As stated above, when any request for image is originated from same website then it's ok, but if the request is coming from another website, then there is a potential problem, as it is creating more work for your web server and reducing the bandwidth.
Solution: HTTP handler will refuse to serve the image or they substitute a dummy image if the referrer header indicates that a request originates from another site.
Add a generic handler from existing item and name it ImageHandler.ashx. Write the code below;
public class ImageHandler : IHttpHandler{
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string imageURL = null;
// Perform a case-insensitive comparison. if (request.UrlReferrer != null)
{
if(String.Compare(request.Url.Host, request.UrlReferrer.Host,true,CultureInfo.InvariantCulture) ==0)
{
// The requesting host is correct. // Allow the image (if it exists). imageURL = request.PhysicalPath;
if (!File.Exists(imageURL))
{
response.Status = "Image Not Found";
response.StatusCode = 404;
}
else {
}
}
}
if (imageURL == null)
{
// No valid image was allowed. // Use the warning image instead. // Rather than hard-code this image, you could // retrieve it from the web.config file // (using the <appSettings> section or a custom // section). imageURL = context.Server.MapPath("~/images/notallowed.gif");
}
// Serve the image // Set the content type to the appropriate image type. response.ContentType = "image/" + Path.GetExtension(imageURL).ToLower();
response.WriteFile(imageURL);
}
// Perform a case-insensitive comparison. if (request.UrlReferrer != null)
{
if(String.Compare(request.Url.Host, request.UrlReferrer.Host,true,CultureInfo.InvariantCulture) ==0)
{
// The requesting host is correct. // Allow the image (if it exists). imageURL = request.PhysicalPath;
if (!File.Exists(imageURL))
{
response.Status = "Image Not Found";
response.StatusCode = 404;
}
else {
}
}
}
if (imageURL == null)
{
// No valid image was allowed. // Use the warning image instead. // Rather than hard-code this image, you could // retrieve it from the web.config file // (using the <appSettings> section or a custom // section). imageURL = context.Server.MapPath("~/images/notallowed.gif");
}
// Serve the image // Set the content type to the appropriate image type. response.ContentType = "image/" + Path.GetExtension(imageURL).ToLower();
response.WriteFile(imageURL);
}
public bool IsReusable
{
get {
return false;
}
}}
Now its time to configure it. For this handler to protect image files, you need to register it to deal with the appropriate file types. Here are the web.config settings that set this up for the .gif and .jpg file types only.
<add verb="*" path="*.gif" type="SimpleHTTPHanlder.ImageHandler,SimpleHTTPHanlder"/><add verb="*" path="*.jpg" type="SimpleHTTPHanlder.ImageHandler,SimpleHTTPHanlder"/>
Now this configuration setting will only allow jpg and gif images, after checking it the request is originating from same website.
So now when we have to request any image , we simple type image URL and we can see that
http://localhost:3238/images/areng.jpg

The one which is not available, is greeted by not found image. Say for this image request which doesn't exists;
http://localhost:3238/images/areds.jpg

So by this HTTP handler for images, we can restrict any request which is not coming from our web site and also increase performance by quicker response time.
{
get {
return false;
}
}}
Now its time to configure it. For this handler to protect image files, you need to register it to deal with the appropriate file types. Here are the web.config settings that set this up for the .gif and .jpg file types only.
<add verb="*" path="*.gif" type="SimpleHTTPHanlder.ImageHandler,SimpleHTTPHanlder"/><add verb="*" path="*.jpg" type="SimpleHTTPHanlder.ImageHandler,SimpleHTTPHanlder"/>
Now this configuration setting will only allow jpg and gif images, after checking it the request is originating from same website.
So now when we have to request any image , we simple type image URL and we can see that
http://localhost:3238/images/areng.jpg
The one which is not available, is greeted by not found image. Say for this image request which doesn't exists;
http://localhost:3238/images/areds.jpg
So by this HTTP handler for images, we can restrict any request which is not coming from our web site and also increase performance by quicker response time.
No comments:
Post a Comment