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.

SubdomainRoute.cs 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.IO;
  2. using System.Linq;
  3. using System.Web;
  4. using System.Web.Mvc;
  5. using System.Web.Routing;
  6. namespace Teknik
  7. {
  8. public class SubdomainRoute : Route
  9. {
  10. public string Subdomain { get; set; }
  11. public SubdomainRoute(string subdomain, string url, IRouteHandler handler)
  12. : base(url, handler)
  13. {
  14. this.Subdomain = subdomain;
  15. }
  16. public SubdomainRoute(string subdomain, string url, RouteValueDictionary defaults, IRouteHandler handler)
  17. : base(url, defaults, handler)
  18. {
  19. this.Subdomain = subdomain;
  20. }
  21. public SubdomainRoute(string subdomain, string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler handler)
  22. : base(url, defaults, constraints, handler)
  23. {
  24. this.Subdomain = subdomain;
  25. }
  26. public SubdomainRoute(string subdomain, string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler handler)
  27. : base(url, defaults, constraints, dataTokens, handler)
  28. {
  29. this.Subdomain = subdomain;
  30. }
  31. public override RouteData GetRouteData(HttpContextBase httpContext)
  32. {
  33. var routeData = base.GetRouteData(httpContext);
  34. if (routeData == null) return null; // Only look at the subdomain if this route matches in the first place.
  35. string subdomain = httpContext.Request.QueryString["sub"]; // A subdomain specified as a query parameter takes precedence over the hostname.
  36. if (subdomain == null)
  37. {
  38. string host = httpContext.Request.Headers["Host"];
  39. subdomain = host.GetSubdomain();
  40. }
  41. else
  42. {
  43. if (routeData.Values["sub"] == null)
  44. {
  45. routeData.Values["sub"] = subdomain;
  46. }
  47. else
  48. {
  49. subdomain = routeData.Values["sub"].ToString();
  50. }
  51. }
  52. //routeData.Values["sub"] = subdomain;
  53. if (Subdomain == "*" || Subdomain == subdomain)
  54. {
  55. return routeData;
  56. }
  57. return null;
  58. }
  59. public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
  60. {
  61. object subdomainParam = requestContext.HttpContext.Request.QueryString["sub"];
  62. if (subdomainParam != null && values["sub"] == null)
  63. values["sub"] = subdomainParam;
  64. return base.GetVirtualPath(requestContext, values); // we now have the route based on subdomain
  65. }
  66. }
  67. }