Skip to content

Instantly share code, notes, and snippets.

@odenijs
Created July 3, 2013 08:03
Show Gist options
  • Save odenijs/5916233 to your computer and use it in GitHub Desktop.
Save odenijs/5916233 to your computer and use it in GitHub Desktop.
A boilerplate template to use for an HttpHandler <httpHandlers> <add verb="GET,POST,WHATEVER" path="SomeEndPoint.ashx" type="MyNamespace.MtHandler, MyAssemblyName" /> </httpHandlers>
public class MyHandler : IHttpHandler
{
private const string CONSTSOMEPARAM = "SomeParam";
public MyHandler(){}
public void ProcessRequest(HttpContext context)
{
// Don't allow this response to be cached by the browser.
// Note, you MIGHT want to allow it to be cached, depending on what you're doing.
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetNoStore();
context.Response.Cache.SetExpires(DateTime.MinValue);
if (ValidateParameters(context) == false)
{
//Internal Server Error
context.Response.StatusCode = 500;
context.Response.End();
return;
}
if (context.User.Identity.IsAuthenticated == false)
{
//Forbidden
context.Response.StatusCode = 403;
context.Response.End();
return;
}
string someParam = context.Request.QueryString[CONSTSOMEPARAM];
SomethingReponse response = SomeService.SomeImportantThing(someParam);
if(response.Header == null || response.Header.Success == false)
{
//Whatever wasn't found
context.Response.StatusCode = 404;
context.Response.End();
return;
}
context.Response.ContentType = "somespecific/mimetype";
context.Response.BinaryWrite();
//or
context.Response.Write();
//or
context.Response.WriteFile();
//or
someImageStream.Save(context.Response.OutputStream);
}
public bool ValidateParameters(HttpContext context)
{
//Validate some stuff...true if cool, false if not
return false;
}
/// <summary>
/// True if this handler can be reused between calls. That's cool if you don't have any class instance data.
/// False if you'd rather get a fresh one.
/// </summary>
public bool IsReusable
{
get
{
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment