The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

UrlExtensions.cs 7.8KB

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