Created
April 20, 2017 09:24
-
-
Save code-atom/d64798c3d54e4af8dc0afdb09be1fdce to your computer and use it in GitHub Desktop.
Custom Http Handler Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class HttpHandlerConfig | |
{ | |
public static void Config(RouteCollection routes) | |
{ | |
routes.Add("CandidateSignatureRoute", new Route("candidate/signature/{id}", new HttpHandlerRouteHandler<CandidateSignatureHandler>())); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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