Skip to content

Instantly share code, notes, and snippets.

@code-atom
Created April 20, 2017 09:24
Show Gist options
  • Save code-atom/d64798c3d54e4af8dc0afdb09be1fdce to your computer and use it in GitHub Desktop.
Save code-atom/d64798c3d54e4af8dc0afdb09be1fdce to your computer and use it in GitHub Desktop.
Custom Http Handler Example
public class CandidateSignatureHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
ICandidateDocument _candidateDocHandler = AppDefaults.Get<ICandidateDocument>();
var routeValues = context.Request.RequestContext.RouteData.Values;
if (routeValues.ContainsKey("id"))
{
var id = Convert.ToInt64(routeValues["id"]);
var signature = _candidateDocHandler.SignatureImage(id);
context.Response.Clear();
//Response type will be the same as the one requested
context.Response.ContentType = "image/png";
//We buffer the data to send back until it's done
context.Response.BufferOutput = true;
if (String.IsNullOrEmpty(signature))
{
context.Response.End();
return;
}
signature = signature.Replace("data:image/png;base64,", String.Empty);
byte[] imageBytes = Convert.FromBase64String(signature);
Image image;
using (MemoryStream ms = new MemoryStream(imageBytes))
{
image = Image.FromStream(ms);
}
image.Save(context.Response.OutputStream, ImageFormat.Png);
context.Response.End();
}
}
}
public static class HttpHandlerConfig
{
public static void Config(RouteCollection routes)
{
routes.Add("CandidateSignatureRoute", new Route("candidate/signature/{id}", new HttpHandlerRouteHandler<CandidateSignatureHandler>()));
}
}
public class HttpHandlerRouteHandler<THandler>
: IRouteHandler where THandler : IHttpHandler, new()
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new THandler();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment