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();
}
Middlewares are registered in the Startup. cs file in a . NET Core application. Configure method handles all HTTP requests.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With