The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UrlExtensions.cs 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. using Microsoft.AspNetCore.Hosting;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.Routing;
  5. using System;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using System.Web;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Hosting;
  11. using Microsoft.AspNetCore.Routing;
  12. namespace Teknik.Utilities.Routing
  13. {
  14. public static class UrlExtensions
  15. {
  16. public static string SubRouteUrl(this IUrlHelper url, string sub, string routeName)
  17. {
  18. return url.SubRouteUrl(sub, routeName, null, string.Empty);
  19. }
  20. public static string SubRouteUrl(this IUrlHelper url, string sub, string routeName, string hostOverride)
  21. {
  22. return url.SubRouteUrl(sub, routeName, null, hostOverride);
  23. }
  24. public static string SubRouteUrl(this IUrlHelper url, string sub, string routeName, object routeValues)
  25. {
  26. return url.SubRouteUrl(sub, routeName, routeValues, string.Empty);
  27. }
  28. /// <summary>
  29. /// Generates a full URL given the specified sub domain and route name
  30. /// </summary>
  31. /// <param name="url"></param>
  32. /// <param name="sub"></param>
  33. /// <param name="routeName"></param>
  34. /// <param name="routeValues"></param>
  35. /// <returns></returns>
  36. public static string SubRouteUrl(this IUrlHelper url, string sub, string routeName, object routeValues, string hostOverride)
  37. {
  38. var linkGen = url.ActionContext.HttpContext.RequestServices.GetService<LinkGenerator>();
  39. var env = url.ActionContext.HttpContext.RequestServices.GetService<IWebHostEnvironment>();
  40. string host = url.ActionContext.HttpContext.Request.Host.Value;
  41. string domain = host;
  42. // Generate a new domain if we aren't in development
  43. if (!env.IsEnvironment(Environments.Development) &&
  44. !string.IsNullOrEmpty(sub))
  45. {
  46. domain = sub + "." + domain.GetDomain();
  47. }
  48. string fullHost = string.Format("{0}://{1}", url.ActionContext.HttpContext.Request.Scheme, domain);
  49. var routeValueDict = new RouteValueDictionary(routeValues);
  50. // Get the endpoint mapping
  51. var mapping = EndpointHelper.GetEndpointMapping(routeName);
  52. if (mapping != null &&
  53. !routeValueDict.ContainsKey("area"))
  54. {
  55. routeValueDict.TryAdd("area", mapping.Area);
  56. }
  57. var path = linkGen.GetPathByAddress(url.ActionContext.HttpContext, routeName, routeValueDict);
  58. return $"{fullHost}{path}";
  59. }
  60. public static string GetUrlParameters(this string url)
  61. {
  62. Uri uri = new Uri(url);
  63. var queryParts = HttpUtility.ParseQueryString(uri.Query);
  64. return queryParts.ToString();
  65. }
  66. public static string SetUrlParameter(this string url, string paramName, string value)
  67. {
  68. return new Uri(url).SetParameter(paramName, value).ToString();
  69. }
  70. public static Uri SetParameter(this Uri url, string paramName, string value)
  71. {
  72. var queryParts = HttpUtility.ParseQueryString(url.Query);
  73. queryParts[paramName] = value;
  74. return new Uri(url.AbsoluteUriExcludingQuery() + '?' + queryParts.ToString());
  75. }
  76. public static string AbsoluteUriExcludingQuery(this Uri url)
  77. {
  78. return url.AbsoluteUri.Split('?').FirstOrDefault() ?? String.Empty;
  79. }
  80. public static string GetSubdomain(this string host)
  81. {
  82. if (host.IndexOf(":") >= 0)
  83. host = host.Substring(0, host.IndexOf(":"));
  84. Regex tldRegex = new Regex(@"\.[a-z]{2,3}\.[a-z]{2}$");
  85. host = tldRegex.Replace(host, "");
  86. tldRegex = new Regex(@"\.[a-z]{2,4}$");
  87. host = tldRegex.Replace(host, "");
  88. if (host.Split('.').Length > 1)
  89. return host.Substring(0, host.IndexOf("."));
  90. else
  91. return string.Empty;
  92. }
  93. public static string GetSubdomain(this IUrlHelper url)
  94. {
  95. string host = url.ActionContext.HttpContext.Request.Host.Value;
  96. // Grab the sub from parameters if it exists
  97. string subParam = url.ActionContext.HttpContext.Request.Query["sub"]; // A subdomain specified as a query parameter takes precedence over the hostname unless on dev
  98. if (string.IsNullOrEmpty(subParam))
  99. {
  100. // If we are on dev and no subparam, we need to set the subparam to the specified sub
  101. subParam = host.GetSubdomain();
  102. }
  103. return subParam;
  104. }
  105. public static string GetDomain(this string host)
  106. {
  107. string domain = host;
  108. var split = host.Split('.'); // split the host by '.'
  109. if (split.Count() > 2)
  110. {
  111. int index = host.IndexOf('.') + 1;
  112. if (index >= 0 && index < host.Length)
  113. domain = host.Substring(index, (host.Length - index));
  114. }
  115. return domain;
  116. }
  117. public static string GetDomain(this Uri uri)
  118. {
  119. string domain = uri.Host;
  120. var split = uri.Host.Split('.'); // split the host by '.'
  121. if (split.Count() > 2)
  122. {
  123. int index = uri.Host.IndexOf('.') + 1;
  124. if (index >= 0 && index < uri.Host.Length)
  125. domain = uri.Host.Substring(index, (uri.Host.Length - index));
  126. }
  127. return domain;
  128. }
  129. public static string GetActive(this IUrlHelper url, params string[] subs)
  130. {
  131. return url.GetActive(null, null, subs);
  132. }
  133. public static string GetActive(this IUrlHelper url, string controller)
  134. {
  135. return url.GetActive(controller, null);
  136. }
  137. public static string GetActive(this IUrlHelper url, string controller, string action, params string[] subs)
  138. {
  139. var curSub = url.GetSubdomain();
  140. var curController = url.ActionContext.RouteData.Values["Controller"]?.ToString();
  141. var curAction = url.ActionContext.RouteData.Values["Action"]?.ToString();
  142. foreach (string sub in subs)
  143. {
  144. if (curSub == sub)
  145. {
  146. if ((string.IsNullOrEmpty(controller) || curController == controller) &&
  147. (string.IsNullOrEmpty(action) || curAction == action))
  148. return "active";
  149. }
  150. }
  151. if (!subs.Any() &&
  152. (string.IsNullOrEmpty(controller) || curController == controller) &&
  153. (string.IsNullOrEmpty(action) || curAction == action))
  154. {
  155. return "active";
  156. }
  157. return string.Empty;
  158. }
  159. public static bool IsValidUrl(this string url)
  160. {
  161. Uri uriResult;
  162. bool result = Uri.TryCreate(url, UriKind.Absolute, out uriResult);
  163. if (result)
  164. {
  165. result = uriResult.IsWellFormedOriginalString();
  166. }
  167. return result;
  168. }
  169. public static string FullURL(this IUrlHelper helper, string virtualPath)
  170. {
  171. var url = string.Format("{0}://{1}{2}", helper.ActionContext.HttpContext.Request.Scheme, helper.ActionContext.HttpContext.Request.Host.ToUriComponent(), helper.Content(virtualPath));
  172. return url;
  173. }
  174. }
  175. }