简体   繁体   English

如何在 .Net Core 中间件中获取当前子域?

[英]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.如何在 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();
        }

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're using Cross-Domain, the best option is to use the Origin from Request-Header.如果您使用跨域,最好的选择是使用来自请求头的源。 Something like:类似的东西:

Request.Headers.TryGetValue("Origin",  out var origin);

and then manipulate the value with split or whatever you like.然后用 split 或任何你喜欢的东西来操纵这个值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.NET 5中,如何在中间件中获取所选路由? - In ASP.NET 5, how do I get the chosen route in middleware? 如何在 .net 核心应用程序中使用中间件操作当前令牌的 ClaimsIdentity? - How to manipulate the ClaimsIdentity of current token using middleware in .net core app? 如何在中间件 ASP.Net Core 5 中获取客户端证书? - How to get Client Certificate in Middleware ASP.Net Core 5? 如何在ASP Net Core 2中获取Firebase IssuerSigningKey - How Do I Get Firebase IssuerSigningKey In Asp net Core 2 .net 核心3中间件或授权属性? 怎么做? - .net core 3 middleware or authorization attribute ? and how to? 如何从HttpContext.Current获取当前的ASP.NET主题? - How do I get the current ASP.NET theme from HttpContext.Current? 如何使用.net-core和Entity Framework Core和Identity从thenInclude中获取特定列? - How do i get specific columns from a thenInclude using .net-core and Entity Framework Core and Identity? 如何在 ASP.NET Core 中获取当前登录的用户 ID? - How to get the current logged in user ID in ASP.NET Core? 如何实现ASP.NET Core中间件来删除请求URL中重复斜杠的实例? - How can I implement an ASP.NET Core middleware to remove instances of repeated slashes in a request URL? 如何从ASP.NET MVC中的自定义帮助器方法中访问当前的System.Web.Routing.RequestContext? - How do you get access to the current System.Web.Routing.RequestContext from within a custom helper method in ASP.NET MVC?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM