How to get the current subdomain inside .Net Core middleware?

How to get the current subdomain for the current request (in the middleware component) in asp.net 5.

I previously used the code below and was looking for something similar.

public static string GetSubDomain()
        {
            string subDomain = String.Empty;

            if (HttpContext.Current.Request.Url.HostNameType == UriHostNameType.Dns)
            {
                subDomain = Regex.Replace(HttpContext.Current.Request.Url.Host, "((.*)(\\..*){2})|(.*)", "$2").Trim().ToLower();
            }

            if (subDomain == String.Empty)
            {

                subDomain = HttpContext.Current.Request.Headers["Host"].Split('.')[0];
            }

            return subDomain.Trim().ToLower();
        }
+4
source share
1 answer

I managed to work out my own answer in the meantime ... commenst appreciated.

private static string GetSubDomain(HttpContext httpContext)
        {
            var subDomain = string.Empty;

            var host = httpContext.Request.Host.Host;

            if (!string.IsNullOrWhiteSpace(host))
            {
                subDomain = host.Split('.')[0];
            }

            return subDomain.Trim().ToLower();
        }
+5
source

Source: https://habr.com/ru/post/1648911/


All Articles