This snippet code is credited to Scott’s Hanselman, This Resolve URL function is used where you want to implement it on your business layer.
Methods:
#region "Image URL helpers" public static string ResolveUrl(string originalUrl) { if (originalUrl == null) return null; // *** Absolute path - just return if (originalUrl.IndexOf("://") != -1) return originalUrl; // *** Fix up image path for ~ root app dir directory if (originalUrl.StartsWith("~")) { string newUrl = ""; if (System.Web.HttpContext.Current != null) newUrl = System.Web.HttpContext.Current.Request.ApplicationPath + originalUrl.Substring(1).Replace("//", "/"); else // *** Not context: assume current directory is the base directory throw new ArgumentException("Invalid URL: Relative URL not allowed."); // *** Just to be sure fix up any double slashes return newUrl; } return originalUrl; } /// Works like Control.ResolveUrl including support for ~ syntax /// but returns an absolute URL. /// /// Any Url, either App relative or fully qualified /// if true forces the url to use https /// public static string ResolveServerUrl(string serverUrl, bool forceHttps) { // *** Is it already an absolute Url? if (serverUrl.IndexOf("://") > -1) return serverUrl; // *** Start by fixing up the Url an Application relative Url string newUrl = ResolveUrl(serverUrl); Uri originalUri = System.Web.HttpContext.Current.Request.Url; newUrl = (forceHttps ? "https" : originalUri.Scheme) + "://" + originalUri.Authority + newUrl; return newUrl; } ////// This method returns a fully qualified absolute server Url which includes /// the protocol, server, port in addition to the server relative Url. /// /// It work like Page.ResolveUrl, but adds these to the beginning. /// This method is useful for generating Urls for AJAX methods /// /// Any Url, either App relative or fully qualified /// public static string ResolveServerUrl(string serverUrl) { return ResolveServerUrl(serverUrl, false); } #endregion
Usage:
sb.AppendFormat("", row.WidgetItemClass); sb.AppendFormat("
");", ProductsService.GetProductUrl(row.ProductID), ResolveServerUrl("~/GetWhiteLabelFile.aspx?whiteLabelFileID=" + row.WidgetItemLinkImageID.ToString())); sb.AppendFormat("
Leave a Reply