Create you first HTTP Handler in ASP.NET 3.5



Similar documents
ASP.NET Using C# (VS2012)

Sitecore Dynamic Links

Engagement Analytics Configuration Reference Guide

Analytics Configuration Reference

Developing ASP.NET MVC 4 Web Applications MOC 20486

Developing ASP.NET MVC 4 Web Applications

Developing ASP.NET MVC 4 Web Applications Course 20486A; 5 Days, Instructor-led

This course provides students with the knowledge and skills to develop ASP.NET MVC 4 web applications.

Transition your MCPD Web Developer Skills to MCPD ASP.NET Developer 3.5 (VB)

Cache Configuration Reference

Developing and Implementing Web Applications with Microsoft Visual C#.NET and Microsoft Visual Studio.NET

Cross Bulk Mailer 6.1 User Guide

Programming in C# with Microsoft Visual Studio 2010

Terms and Definitions for CMS Administrators, Architects, and Developers

Microsoft.Realtests v by.ERICA.50q

Proof of Concept. A New Data Validation Technique for Microsoft ASP.NET Web Applications. Foundstone Professional Services

MVC Implementations Playbook. Version 0.92

MS 20487A Developing Windows Azure and Web Services

Sitecore Security Hardening Guide


Archive Manager Exchange Edition OWA Troubleshooting

DotNet Web Developer Training Program

To install Multifront you need to have familiarity with Internet Information Services (IIS), Microsoft.NET Framework and SQL Server 2008.

INSTALLATION AND CONFIGURATION MANUAL ENCODER

Creating Form Rendering ASP.NET Applications

Walkthrough: Creating and Using an ASP.NET Web Service in Visual Web Developer

Logi Ad Hoc Reporting Configuration for Load Balancing (Sticky Sessions)

RSS Feed from an Access Database

Design and Functional Specification

Developing Microsoft SharePoint Server 2013 Advanced Solutions MOC 20489

Click Studios. Passwordstate. Upgrade Instructions to V7 from V5.xx

This three-day instructor-led course provides students with the tools to extend Microsoft Dynamics CRM 4.0.

Cross Bulk Mailer 5.4 User Guide

Developing a Web Server Platform with SAPI Support for AJAX RPC using JSON

MS Enterprise Library 5.0 (Logging Application Block)

multiple placeholders bound to one definition, 158 page approval not match author/editor rights, 157 problems with, 156 troubleshooting,

Developing Microsoft SharePoint Server 2013 Advanced Solutions. Version: Demo. Page <<1/8>>

This class is intended for experienced software developers who understand object-oriented programming (OOP) and C# or VB.NET.

Developing Windows Azure and Web Services

This module provides an overview of service and cloud technologies using the Microsoft.NET Framework and the Windows Azure cloud.

Microsoft Dynamics CRM Security Provider Module

Installing the ASP.NET VETtrak APIs onto IIS 5 or 6

AxCMS.net Help & Support Center > Installation & Configuration > Configuration > WebDAV. Table Of Contents -WebDAV

Visual COBOL ASP.NET Shopping Cart Demonstration

TIBCO Spotfire Web Player 6.0. Installation and Configuration Manual

metaengine DataConnect For SharePoint 2007 Configuration Guide

OTP Server. Integration module. Nordic Edge AD Membership Provider for Microsoft ASP.NET. Version 1.0, rev. 6. Nordic Edge

Configuring Microsoft IIS 5.0 With Pramati Server

Course 20489B: Developing Microsoft SharePoint Server 2013 Advanced Solutions OVERVIEW

Chapter 1: General Introduction What is IIS (Internet Information Server)? IIS Manager: Default Website IIS Website & Application

DE-20489B Developing Microsoft SharePoint Server 2013 Advanced Solutions

LearningServer Portal Manager

The end. Carl Nettelblad

Kentico 8 Certified Developer Exam Preparation Guide. Kentico 8 Certified Developer Exam Preparation Guide

Acano solution. Acano Manager R1.1 FAQs. Acano. December G

Developing Microsoft SharePoint Server 2013 Advanced Solutions

DEPLOYMENT GUIDE Version 2.1. Deploying F5 with Microsoft SharePoint 2010

VB.NET - WEB PROGRAMMING

Expanded contents. Section 1. Chapter 2. The essence off ASP.NET web programming. An introduction to ASP.NET web programming

Ligero Content Delivery Server. Documentum Content Integration with

R i o L i n x s u p p o r r i o l i n x. c o m 1 / 3 0 /

João Diogo Almeida Premier Field Engineer Microsoft Corporation

Developing Microsoft SharePoint Server 2013 Advanced Solutions

JOSSO 2.4. Internet Information Server (IIS) Tutorial

Access It! Universal Web Client Integration

EPiServer Operator's Guide

DEPLOYMENT GUIDE Version 1.1. Deploying F5 with IBM WebSphere 7

Course Outline: Course 20489B: Developing Microsoft SharePoint Server 2013 Advanced Solutions

Dynamic Web Programming BUILDING WEB APPLICATIONS USING ASP.NET, AJAX AND JAVASCRIPT

Tableau Server Trusted Authentication

Novell Identity Manager

Custom Error Pages in ASP.NET Prabhu Sunderaraman

Richmond Web Services Installation Guide Web Reporting Version 10.0

Summary This article contains information about an installation of EdgeSight 5.4 Web Server using SQL 2008 R2 (DB and RS) in a lab environment.

Building a Multi-Threaded Web Server

Installation for WEB Server Windows 2003

Administrator's Guide

How to test and debug an ASP.NET application

Installation Documentation Smartsite ixperion 1.3

Internet Information TE Services 5.0. Training Division, NIC New Delhi

Describe how to utilize the Publishing API to access publishing settings and content.

Creating XML Report Web Services

Adding ELMAH to an ASP.NET Web Application

Programming Fundamentals of Web Applications Course 10958A; 5 Days

XS8602_ASPNET_SessionStateStore.pptx.ppt Page 1 of 19

Building a Scale-Out SQL Server 2008 Reporting Services Farm

Tableau Server Trusted Authentication

SharePoint for Developers. Lunch and Learn

Click Studios. Passwordstate. Installation Instructions

Finding and Preventing Cross- Site Request Forgery. Tom Gallagher Security Test Lead, Microsoft

General principles and architecture of Adlib and Adlib API. Petra Otten Manager Customer Support

ACTIVE DIRECTORY WEB SERVICE USER GUIDE LAST UPDATED: January 4, 2013

FTP, IIS, and Firewall Reference and Troubleshooting

JWIG Yet Another Framework for Maintainable and Secure Web Applications

Intellicus Single Sign-on

Transcription:

Create you first HTTP Handler in ASP.NET 3.5 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. 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: 1) Page Handler (.aspx) Handles Web pages 2) User Control Handler (.ascx) Handles Web user control pages 3) Web Service Handler (.asmx) Handles Web service pages 4) Trace Handler (trace.axd) Handles trace functionality Why we need to create our own HTTP Handler: Sometime we need to avoid ASP.NET full page processing model, which saves lot of overheads, as ASP.NET web form model has to go through many steps such as creating web page objects, persisting view state etc. What we are interested into is to develop some low level interface that provides access to objects like Request and Response but doesn t use the full control based web form model discussed above. Examples: 1) Dynamic image creator Use the System.Drawing classes to draw and size your own images. 2) RSS Create a handler that responds with RSS-formatted XML. This would allow you to add RSS feed capabilities to your sites. 3) render a custom image, 4) perform an ad hoc database query, 5) Return some binary data. These examples extend the ASP.NET architecture but bypass the web-page model. The result is a leaner, more efficient component.

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> 1) 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 2).config: Handled by HttpForbiddenHandler 3).cs: Handled by HttpForbiddenHandler 4).aspx: Handled by PageHandlerFactory, which isn t a HTTP handler rather it s a class that will create the appropriate HTTP handler. What is HTTP module: Help in processing of page request by handing application events, similar to what global.asax does. A request can pass through many HTTP modules but is being handled by only one HTTP handlers.

Use of HTTP Modules: 1) ASP.NET uses HTTP modules to enable features like caching, authentication, error pages etc. 2) <add> and <remove> tags can be used to add and inactive any http module from <httpmodule> section of a configuration file. <httpmodules> <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: 1) HTTP handler plays same role what ISAPI extension 2) HTTP module plays same role what ISAPI filters does. How to write custom HTTP handler: Step 1: What all we need to know before writing handlers

There are two type of handler you actually can make 1) Synchronous handler, which implement IHttpHandler interface 2) 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 Further these Interfaces require us to implement the ProcessRequest method and the IsReusable property. 1) 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. 2) 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 2: Create a ASP.NET web application and name it: SimpleHTTPHanlder 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; 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>"); #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 1) Verb: indicates whether the request is an HTTP POST or HTTP GET request (use * for all requests). 2) Path : indicates the file extension that will invoke the HTTP handler 3) 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; 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); 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 configration 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 resposne time. Hope You enjoyed, Cheers