Configuring ASP.Net MVC for the Microsoft Charting Control
March 23, 2011 2 Comments
There are a couple of gotchas when using either the .NET 3.5 add-on charting control or the one that ships with .NET 4.0 with ASP.Net MVC. These can lead to some head-scratching and consternation at deployment time if you don’t know about them.
MVC Paths Break Chart Images
MVC paths are RESTful which means that a lot of the path in a URL is likely to be arguments to a controller rather than an actual path to a resource. Unfortunately, by default these paths confuse the charting control which assumes that the path in the URL leads to the resource hosting the control. The net result is that invoking RESTful methods on your controller causes your chart images go missing. The solution is to use a little bit of regular expression to create a “ignore” routing rule in Global.asax.cs for ChartImg.axd which is the virtual file that generates the charting control images.
public static void RegisterRoutes( RouteCollection routes ) { //MSFT charting control image genertor RouteTable.Routes.IgnoreRoute( "{*chartimg}", new { chartimg = @".*/ChartImg\.axd(/.*)?" } ); //standard default route ignore rule RouteTable.Routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); }
Charting Control Wants to Write to Your Application Root
Another problem that will show up at deployment time is that the charting control wants to write cached images to the root of your application by default and it wants to do this in the security context of the invoking user. That is, in order for this default to work, anonymous web users need write access to the root of your application. This is a bad, bad, bad idea.
Fortunately this behavior can be configured in the Web.config. You can change the cache directory or use global application memory or session to store the images. Using memory has the advantage that you don’t need to give anybody permission to write into the server file system.
<configuration> <appSettings> <add key="ChartImageHandler" value="storage=memory;timeout=20;privateImages=false" /> </appSettings> <configuration>
The full set of configuration options are described on MSDN.