Click here to Skip to main content
12,754,391 members (29,680 online)
Click here to Skip to main content
Articles » Web Development » ASP.NET » General » Revisions
Add your own
alternative version


138 bookmarked
Posted 25 Mar 2012 Advanced Generic Handler ASHX

, 26 Mar 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Take your Generic Handlers to the next level...
This is an old version of the currently published article.


In we have something that is usually overlloked 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 endpont.
This is an completelly worked out Generic Handler that trully knows how to handle your http (AJAX and not) requests.

Download Source Code


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:

  • 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 eather 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 hadler 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:


Calling the Handler from the browser URL

Using this handles is very simple:

  1. Create a new Generic Handler
  2. Clear everything inside the handler class
  3. Inherit from my Handler class
  4. DONE! Now you only need to add your methods.

Lets create a very simple example that receives a name and returns a string (see on the project).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using App.Utilities.Web.Handlers;

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:


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:

{ method: 'The method you want to call', args: { the arguments to pass } }
Be aware that everything is case sensitive!
	url: 'MyFirstHandler.ashx',
	type: 'GET',
	data: { method: 'GreetMe', args: { name: 'AlexCode'} },
	success: function (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:

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:
public object GiveMeSomeHTML(string text)
	StringBuilder sb = new StringBuilder();
	sb.Append("<head><title>My Handler!</title></head>");
This is a HTML page returned from the Handler
The text passed was: " + text + "

	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

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.


  • 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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Switzerland Switzerland
Senior IT Consultant working in Switzerland as Senior Software Engineer.

Find more at on my blog.

You may also be interested in...

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
GeneralMy vote of 5 Pin
Anurag Gandhi27-Mar-12 19:05
memberAnurag Gandhi27-Mar-12 19:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
QuestioncURL query? Pin
bradut18-Oct-15 19:35
memberbradut18-Oct-15 19:35 
AnswerRe: cURL query? Pin
AlexCode19-Oct-15 6:49
professionalAlexCode19-Oct-15 6:49 
GeneralRe: cURL query? Pin
bradut19-Oct-15 10:41
memberbradut19-Oct-15 10:41 
GeneralRe: cURL query? Pin
AlexCode19-Oct-15 23:30
professionalAlexCode19-Oct-15 23:30 
GeneralRe: cURL query? Pin
bradut20-Oct-15 7:39
memberbradut20-Oct-15 7:39 
GeneralRe: cURL query? Pin
AlexCode20-Oct-15 10:01
professionalAlexCode20-Oct-15 10:01 
Questionjson array to generic handler Pin
snow_cap3-Jul-14 12:13
membersnow_cap3-Jul-14 12:13 
AnswerRe: json array to generic handler Pin
AlexCode4-Jul-14 3:59
professionalAlexCode4-Jul-14 3:59 
GeneralMy vote of 1 Pin
Member 1043844613-Feb-14 1:57
memberMember 1043844613-Feb-14 1:57 
GeneralRe: My vote of 1 Pin
AlexCode13-Feb-14 23:56
professionalAlexCode13-Feb-14 23:56 
GeneralRe: My vote of 1 Pin
Member 1043844614-Feb-14 0:39
memberMember 1043844614-Feb-14 0:39 
GeneralRe: My vote of 1 Pin
AlexCode16-Feb-14 22:51
professionalAlexCode16-Feb-14 22:51 
GeneralMy vote of 1 Pin
Matty2213-Jun-13 22:06
memberMatty2213-Jun-13 22:06 
GeneralRe: My vote of 1 Pin
AlexCode13-Jun-13 22:25
professionalAlexCode13-Jun-13 22:25 
GeneralRe: My vote of 1 Pin
AbsCode4-Aug-13 2:47
memberAbsCode4-Aug-13 2:47 
GeneralMy vote of 4 Pin
Sniper9010-Jun-13 0:09
memberSniper9010-Jun-13 0:09 
QuestionJson.NET? Pin
ahagel28-May-13 19:24
memberahagel28-May-13 19:24 
AnswerRe: Json.NET? Pin
AlexCode28-May-13 23:15
professionalAlexCode28-May-13 23:15 
GeneralMy vote of 1 Pin
abforce27-May-13 11:39
memberabforce27-May-13 11:39 
GeneralRe: My vote of 1 Pin
AlexCode27-May-13 11:52
professionalAlexCode27-May-13 11:52 
GeneralRe: My vote of 1 Pin
abforce28-May-13 7:00
memberabforce28-May-13 7:00 
GeneralRe: My vote of 1 Pin
AlexCode28-May-13 8:05
professionalAlexCode28-May-13 8:05 
GeneralRe: My vote of 1 Pin
HaBiX29-May-13 8:59
memberHaBiX29-May-13 8:59 
GeneralRe: My vote of 1 Pin
AlexCode29-May-13 21:47
professionalAlexCode29-May-13 21:47 
GeneralRe: My vote of 1 Pin
HaBiX29-May-13 22:46
memberHaBiX29-May-13 22:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170217.1 | Last Updated 26 Mar 2012
Article Copyright 2012 by AlexCode
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid