.NET Get Relative URL - ResolveClientUrl - MVC and WebForms

I needed to get the relative path to an image based on the URL in a static class.

Typically I would just use Page.ResolveClientUrl but that does not work in a class that does not inherit the page object.  Here is a snippet of code to cast HttpContext to a Page object. 

Webforms: This the code using in ASP.NET Webforms to get the relative URL in a base class
//Get the Full Path based on the page.             
//This will return /folder/image.jpg or something like ../folder/image.jpg
HttpContext CTX = HttpContext.Current;
System.Web.UI.Page page = (System.Web.UI.Page)HttpContext.Current.Handler;
var ImageFullPath = page.ResolveClientUrl(folderName + @"/" + imageName);
MVC: This the code using in ASP.NET MVC to get the relative URL in a base class
//Create the Chart and save it
HttpContext CTX = HttpContext.Current;            
var ServerPath = CTX.Server.MapPath(ImgTempFolder);
var ImgName = c.makeTmpFile(ServerPath); //This is using ChartDirector. Replace your URL here.           

var VPath = VirtualPathUtility.ToAbsolute(ImgTempFolder) + ImgName;
return VPath;			
Comments are closed