Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the current subdomain within .Net Core middleware?

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

I previously used the code below and 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();
        }
like image 950
Mark Redman Avatar asked Jul 24 '16 05:07

Mark Redman


People also ask

Where do you find the middleware in .NET Core?

Middlewares are registered in the Startup. cs file in a . NET Core application. Configure method handles all HTTP requests.

Can you name any built in middleware which you used in .NET Core?

A middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed in each request.

What is app UseRouting ()?

UseRouting adds route matching to the middleware pipeline. This middleware looks at the set of endpoints defined in the app, and selects the best match based on the request. UseEndpoints adds endpoint execution to the middleware pipeline. It runs the delegate associated with the selected endpoint.


1 Answers

I have managed to work out my own answer in the meantime...comments 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();
        }
like image 146
Mark Redman Avatar answered Sep 26 '22 22:09

Mark Redman