Last active
August 29, 2015 14:19
-
-
Save cdroulers/9cc8f7094923f14ad5c5 to your computer and use it in GitHub Desktop.
SvgHandler.cs
This file contains 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 SvgHandler : IHttpHandler | |
{ | |
public void ProcessRequest(HttpContext context) | |
{ | |
var fileName = Path.GetFileName(context.Request.AppRelativeCurrentExecutionFilePath) ?? string.Empty; | |
var svgIndex = fileName.LastIndexOf(".svg", StringComparison.InvariantCultureIgnoreCase); | |
var classIndex = fileName.IndexOf('.'); | |
string[] classNames = new string[0]; | |
string svgPath; | |
if (svgIndex != classIndex) | |
{ | |
classNames = fileName.Substring(classIndex, svgIndex - classIndex).Split('.'); | |
svgPath = context.Server.MapPath(fileName.Substring(0, classIndex) + ".svg"); | |
} | |
else | |
{ | |
svgPath = context.Server.MapPath(fileName); | |
} | |
context.Response.ContentType = "image/svg+xml"; | |
context.Response.Cache.SetExpires(DateTime.UtcNow.AddYears(1)); | |
if (!classNames.Any()) | |
{ | |
// Early return if no changes need to be done. | |
context.Response.WriteFile(svgPath); | |
return; | |
} | |
var svgDocument = new XmlDocument(); | |
svgDocument.Load(svgPath); | |
if (svgDocument.DocumentElement != null) | |
{ | |
var attributes = svgDocument.DocumentElement.Attributes; | |
var classAttribute = attributes["class"]; | |
if (classAttribute == null) | |
{ | |
classAttribute = svgDocument.CreateAttribute("class"); | |
attributes.Append(classAttribute); | |
} | |
classAttribute.Value = string.Join(" ", classNames); | |
} | |
using (var memoryStream = new MemoryStream()) | |
{ | |
svgDocument.Save(memoryStream); | |
context.Response.BinaryWrite(memoryStream.ToArray()); | |
} | |
} | |
public bool IsReusable | |
{ | |
get { return true; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment