Marco Valsecchi

IE9 CSS3 gradient support: .NET workaround solution

23 marzo 2011 • ⏲️ 1 min.

This is the .NET version of this PHP workaround to support CSS3 gradient on IE9.

I used a generic handler called “gradient.ashx”; here the source code:

 <%@ WebHandler Language="C#" Class="gradient" %> 
   
 using System;  
 using System.Web;  
 using System.Xml.Linq;  
   
 public class gradient : IHttpHandler  
 {     
   public void ProcessRequest(HttpContext context)  
   {  
     context.Response.ContentType = "image/svg+xml; charset=utf-8";  
   
     string fromStop = context.Request.QueryString["from"] != null ? context.Request.QueryString["from"] : "000000";  
     string toStop = context.Request.QueryString["to"] != null ? context.Request.QueryString["to"] : "000000";  
   
     XNamespace w3 = "http://www.w3.org/2000/svg";  
   
     var svg = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),  
       new XElement(w3 + "svg",  
         new XAttribute(XNamespace.Xmlns + "xlink", "http://www.w3.org/1999/xlink"),  
         new XAttribute("version", "1.0"),  
         new XAttribute("preserveAspectRatio", "none"),  
         new XAttribute("width", "100%"),  
         new XAttribute("height", "100%"),  
         new XElement(w3 + "defs",  
           new XElement(w3 + "linearGradient",  
             new XAttribute("id", "linear-gradient"),  
             new XAttribute("x1", "0%"),  
             new XAttribute("y1", "0%"),  
             new XAttribute("x2", "0%"),  
             new XAttribute("y2", "100%"),  
             new XAttribute("spreadMethod", "pad"),  
             new XElement(w3 + "stop",  
               new XAttribute("offset", "0%"),  
               new XAttribute("stop-color", "#" + fromStop),  
               new XAttribute("stop-opacity", "1")  
             ),  
             new XElement(w3 + "stop",  
               new XAttribute("offset", "100%"),  
               new XAttribute("stop-color", "#" + toStop),  
               new XAttribute("stop-opacity", "1")  
             )  
           )  
         ),  
         new XElement(w3 + "rect",  
           new XAttribute("width", "100%"),  
           new XAttribute("height", "100%"),  
           new XAttribute("style", "fill: url(#linear-gradient);")  
         )  
       )  
     );  
   
     context.Response.Write(svg.ToString());  
   }  
   
   public bool IsReusable  
   {  
     get  
     {  
       return false;  
     }  
   }  
   
 }  

Upload it in the same css folder and call the URL like so:

 gradient.ashx?from=f00&to=00f  

Marco Valsecchi

"Man is still the most extraordinary computer of all" (J.F. Kennedy)