我正在使用Url.RouteUrl("My_Route", new RouteValueDictionary(new { some = "value" }),"http","hostname")
,现在我需要从 url 获取主机名,但只是顶级域。例如,我正在使用 ui.foo.local 运行我的网站,并且我需要将 url 路由到 foo.local。在 mvc 或 c# 中是否有内置的方法来执行此操作?
问问题
592 次
1 回答
1
我遇到了这个问题,并写了一个小域 Url 拆分器类,因为我找不到任何简单的方法来做到这一点。没有花太长时间,很高兴得到一些反馈。你像这样使用它:
var splitter = new DomainSplitter("http://stackoverflow.com");
var domain = splitter.DomainPart;
课程在这里:
public class DomainSplitter {
public string DomainPart { get; private set; }
public string SubDomainPart { get; private set; }
public string SchemePart { get; private set; }
public string QueryPart { get; private set; }
public DomainSplitter(string url) {
if (string.IsNullOrEmpty(url)) {
throw new Exception("urlString or expected sub domain were null or empty");
}
if (url.Contains("://")) {
ShemePart = url.Split(':')[0] + "://";
url = url.Remove(0, FirstPart.Length);
}
var endOfDomainIndex = url.IndexOfAny("?/".ToCharArray());
if (endOfDomainIndex == -1) {
endOfDomainIndex = url.Length;
}
int startOfDomainIndex;
var domainStub = url.Substring(0, endOfDomainIndex);
var noOfDots = domainStub.Length - domainStub.Replace(".", "").Length;
switch (noOfDots) {
case 0:
startOfDomainIndex = 0;
break;
case 1:
startOfDomainIndex = 0;
if (url.Contains("localhost")) {
startOfDomainIndex = url.IndexOf(".") + 1;
}
break;
default:
startOfDomainIndex = url.IndexOf(".") + 1;
break;
}
if (url.Contains("?")) {
QueryPart = "?" + url.Split('?')[1];
}
else {
QueryPart = "";
}
SubDomainPart = startOfDomainIndex > 0 ? url.Substring(0, startOfDomainIndex - 1) : "";
DomainPart = url.Substring(startOfDomainIndex, endOfDomainIndex - startOfDomainIndex);
}
}
于 2012-09-10T19:49:46.517 回答