Skip to content

Instantly share code, notes, and snippets.

@cdroulers
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdroulers/9cc8f7094923f14ad5c5 to your computer and use it in GitHub Desktop.
Save cdroulers/9cc8f7094923f14ad5c5 to your computer and use it in GitHub Desktop.
SvgHandler.cs
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