Created
November 5, 2013 22:16
-
-
Save DTTerastar/7327308 to your computer and use it in GitHub Desktop.
ResolveUrls without page reference. Makes rooted relative urls. Has very simple syntax with anonymous objects for query string params.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string GlobalResolveUrl(string url) | |
{ | |
return (new Uri(HttpContext.Current.Request.Url, ResolveUrl(url))).GetLeftPart(UriPartial.Query); | |
} | |
public static string GlobalResolveUrl(string url, object queryStringParams) | |
{ | |
return (new Uri(HttpContext.Current.Request.Url, ResolveUrl(url, queryStringParams))).GetLeftPart(UriPartial.Query); | |
} | |
public static string ResolveUrl(string url) | |
{ | |
if (!url.StartsWith("~/")) return url; | |
var appDomainAppVirtualPath = HttpRuntime.AppDomainAppVirtualPath; | |
var resolved = url.Substring(1); | |
return appDomainAppVirtualPath == "/" ? resolved : appDomainAppVirtualPath + resolved; | |
} | |
public static string ResolveUrl(string url, object queryStringParams) | |
{ | |
var sb = new StringBuilder(ResolveUrl(url)); | |
bool firstParam = !url.Contains("?"); | |
foreach (var p in queryStringParams.ToDictionary()) | |
{ | |
sb.Append(firstParam ? '?' : '&'); | |
sb.Append(HttpUtility.UrlEncode(p.Key)); | |
firstParam = false; | |
if (p.Value == null) continue; | |
sb.Append('='); | |
sb.Append(HttpUtility.UrlEncode(p.Value.ToString())); | |
} | |
return sb.ToString(); | |
} | |
public static Dictionary<string, object> ToDictionary(this object values) | |
{ | |
return values == null ? null : TypeDescriptor.GetProperties(values).Cast<PropertyDescriptor>().ToDictionary(a => a.Name, a => a.GetValue(values)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment