ASP.
NET Advanced Generic Handler ASHX - CodeProject
http://www.codeproject.com/Articles/353260/ASP-NET-Advanced-Gene...
8,621,158 members and growing! (63,937 online)
TanzeelurRehman
2.2K
Sign out
Home
Articles
Quick Answers
Discussions
Learning Zones
Features
Help!
The Lounge
3
Search site
Web Development ASP.NET General
ASP.NET Advanced Generic Handler ASHX
By AlexCode | 3 Apr 2012
C# ASP.NET .NET Dev Ajax Beginner Intermediate Advanced jQuery JSON
Licence First Posted Views Downloads Bookmarked
CPOL 26 Mar 2012 4,684 156 29 times
See Also
More like this More by this author
,+
Take your Generic Handlers to the next level...
Article Browse Code Stats Revisions (8) Alternatives
4.91 (8 votes)
Download AdvancedHandler1.1.zip - 100.9 KB
Add your own alternative version
Introduction
In ASP.NET, we have something that is usually overlooked that is called Generic Handlers. I see a lot o f people using pages to process AJAX requests when we can use this much less expensive endpoint. This is an completely worked out Generic Handler that truly knows how to handle your http (AJAX and not) requests.
Background
For a long time I used plain Generic Handlers (ASHX files) to handle my AJAX requests but it felt stupid and painful. I mean, the functionality was there but the whole process of handling the requests wasn't straight forward. So I made a list of the things I would like to have on and handler:
NEW! Support for complex objects as method argument
Now you can put your custom classes on the handler methods arguments. Automatically hydrates the class and all its nested types!! Standard way to parse the query string Transparently handle multiple methods within the same handler Support methods with multiple typed arguments, not just strings Support Methods that receive lists as an argument Support passing less arguments than the method is expecting (like optional parameters) Transparently reply either POSTs or GETs Support default object serialization to JSON but still let me override it on each method Return application/json by default but still let me override it on each method Support jQuery $.ajax request Support request by query string (URL right on the browser) A way to visualize the methods the handler supports (like webservices do) Extensible And that's it... I can tell you in advance that it already does all this and maybe more.
Using the code
List the Handler methods
I've provided a very basic way of listing the methods the Handler exposes. This is specially useful to test if the handler is working correctly (like on webservices). Do do so just append ?help at the end of the handler URL:
Collapse | Copy Code
Related Articles
http://localhost/mydemohandler.ashx?help
Calling the Handler from the browser URL
Using this handles is very simple: 1. 2. 3. 4. Create a new Generic Handler Clear everything inside the handler class Inherit from my Handler class DONE! Now you only need to add your methods.
Let's create a very simple example that receives a name and returns a string (see on the project).
1 of 4
4/3/2012 10:34 AM
ASP.NET Advanced Generic Handler ASHX - CodeProject
http://www.codeproject.com/Articles/353260/ASP-NET-Advanced-Gene...
Collapse | Copy Code
using using using using using
System; System.Collections.Generic; System.Linq; System.Web; App.Utilities.Web.Handlers;
A generic Image-From-DB class for ASP.NET Generic sorting of customer objects for ObjectDataSource (ASP.NET) ASP.NET Server Side Handler for HTML5 Valums Ajax file Upload Upload and Convert Video File to Flash Video (flv) and Progressive Streaming using ASP.NET Handler Advanced Data Caching features in ASP.NET ASP.NET 1.1 Panel Enter Key Handler Generic InvocationHelper Manage ASP.NET Server Controls, Event Handlers, and Server-Side Validation Using XML and XSLT Advanced Paging GridView with ASP.NET 2.0/3.5 Simple JSON Handler for ASP.NET 2.0 to Implement AJAX Functionality
namespace CodeProject.GenericHandler { public class MyFirstHandler : BaseHandler { // I don't bother specifying the return type, it'll be serialized anyway public object GreetMe(string name) { return string.Format("Hello {0}!", name); } } }
To call this method through a URL use:
Collapse | Copy Code
Generic Event Arguments Using generics for calculations
MyFirstHandler.ashx?method=GreetMe&name=AlexCode
AJAX Request using jQuery
If you want to use jQuery AJAX method you just need to know the object the handler is expecting to get. On the data property of the $.ajax request you must pass something like:
Collapse | Copy Code
{ method: 'The method you want to call', args: { the arguments to pass } }
Be aware that everything is case sensitive!
Collapse | Copy Code
$.ajax({ url: 'MyFirstHandler.ashx', type: 'GET', data: { method: 'GreetMe', args: { name: 'AlexCode'} }, success: function (data) { alert(data); } });
Writing a method that returns HTML
Like I said on my intention points above, I need to have some methods that return whatever I want like HTML, XML, images, files, etc... The default behavior of the handler is to return JSON so, by method, we need to explicitly say that we want to handle things our way. For that just use these lines anywhere within the method:
Collapse | Copy Code
SkipContentTypeEvaluation = true; SkipDefaultSerialization = true; // you can specify the response content type as follows context.Response.ContentType = "text/html";
Lets see an example on how we could write a method on the handler that returns HTML:
Collapse | Copy Code
public object GiveMeSomeHTML(string text) { StringBuilder sb = new StringBuilder(); sb.Append("<head><title>My Handler!</title></head>"); sb.Append("<body>"); sb.Append(" This is a HTML page returned from the Handler "); sb.Append(" The text passed was: " + text + " "); sb.Append("</body>"); context.Response.ContentType = "text/html"; SkipContentTypeEvaluation = true; SkipDefaultSerialization = true; return sb.ToString(); }
Optional Parameters and nullable types
All parameters in the methods are optional. If they're not passed their default value is assigned. Also all parameters can be nullable. In this case the default value will be null.
Support for complex types
2 of 4
4/3/2012 10:34 AM
ASP.NET Advanced Generic Handler ASHX - CodeProject
http://www.codeproject.com/Articles/353260/ASP-NET-Advanced-Gene...
Say you have a JSON object and a class server side that maps it. Hydrating this class server side is a pain. Usually we pass each property as an argument of the method on the Handler, instantiate a new instance of the class and set the properties one by on... a pain right? NO MORE! This handler now supports automatic class instance creation and property set. Something I like to call Object Hydratation! :) And there's more! If this class have properties that also expose other custom classes they will be hydrated too!! Just make sure all classes have a public default constructorr
Collapse | Copy Code
// Now you can have method like this public object SendPersonData(Person person) { return person.Name; } // your ajax call object would be something like ... data: { method: 'SendPersonData', args:{ person: { Name: 'Alex' } } } ...
Please have a look at the attached code sample for more examples.
Points of Interest
I can say that this handler already saved me a good amount of development and maintenance hours. Currently all my AJAX requests point to a method on an handler like this.
History ;
v1.1 - Added support for complex arguments v1.0 - The first wide open version This is a work in progress, I keep improving it regularly. I have no doubt that you'll try to use this in scenarios I haven't predicted. Please send me your requests and desires, I'll do my best to implement them.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
About the Author
AlexCode Alexandre Simes is a freelancer working as senior software architect with the focus on Financial Web Applications. Find more about me on my blog.
Architect AlexCode Portugal Member
Article Top
Rate this:
Poor
Excellent
Vote
Comments and Discussions
Add a Comment or Question
Search this forum Profile popups Noise
Medium
Go Per page
25
Layout
Normal
Update
Refresh
First Prev Next
3 of 4
4/3/2012 10:34 AM
ASP.NET Advanced Generic Handler ASHX - CodeProject
http://www.codeproject.com/Articles/353260/ASP-NET-Advanced-Gene...
Handler vs WCF Re: Handler vs WCF Re: Handler vs WCF Last Visit: 10:00 1 Jan '00 General News Last Update: 10:28 3 Apr '12 Suggestion Question Bug
Nitin Sawant AlexCode Nitin Sawant
11:41 27 Mar '12 16:05 27 Mar '12 18:03 27 Mar '12 1
Answer
Joke
Rant
Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Permalink | Advertise | Privacy | Mobile Web04 | 2.5.120402.1 | Last Updated 2 Apr 2012 Layout: fixed | fluid Article Copyright 2012 by AlexCode Everything else Copyright CodeProject, 1999-2012 Terms of Use
4 of 4
4/3/2012 10:34 AM