RewriteSubdomainRule.cs 1.0 KB

1234567891011121314151617181920212223242526272829
  1. using Microsoft.AspNetCore.Rewrite;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. namespace WebPortal.Extensions
  8. {
  9. public class RewriteSubdomainRule : IRule
  10. {
  11. public void ApplyRule(RewriteContext context)
  12. {
  13. var request = context.HttpContext.Request;
  14. var host = request.Host.Host;
  15. // Check if the host is subdomain.domain.com or subdomain.localhost for debugging
  16. if (Regex.IsMatch(host, @"^[A-Za-z\d]+\.(?:[A-Za-z\d]+\.[A-Za-z\d]+|localhost)$"))
  17. {
  18. string subdomain = host.Split('.')[0];
  19. //modifying the request path to let the routing catch the subdomain
  20. context.HttpContext.Request.Path = "/subdomain/" + subdomain + context.HttpContext.Request.Path;
  21. context.Result = RuleResult.ContinueRules;
  22. return;
  23. }
  24. context.Result = RuleResult.ContinueRules;
  25. return;
  26. }
  27. }
  28. }