回答:
HttpContext.Current.Request.Urlは、URLに関するすべての情報を取得できます。また、URLをフラグメントに分解できます。
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
GetLeftPartメソッドは、URI文字列の左端の部分を含み、partで指定された部分で終了する文字列を返します。
URIのスキームと権限セグメント。
まだ疑問に思っている人のために、より完全な答えはhttp://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/で入手できます。
public string FullyQualifiedApplicationPath
{
get
{
//Return variable declaration
var appPath = string.Empty;
//Getting the current context of HTTP request
var context = HttpContext.Current;
//Checking the current context content
if (context != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
context.Request.Url.Scheme,
context.Request.Url.Host,
context.Request.Url.Port == 80
? string.Empty
: ":" + context.Request.Url.Port,
context.Request.ApplicationPath);
}
if (!appPath.EndsWith("/"))
appPath += "/";
return appPath;
}
}
context.Request.Url.Port == 80
ことにより、(context.Request.Url.Port == 80 && context.Request.Url.Scheme == "http") || (context.Request.Url.Port == 443 && context.Request.Url.Scheme == "https")
または使用の答えの下に
たとえば、URLがhttp://www.foobar.com/Page1の場合
HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"
HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"
HttpContext.Current.Request.Url.Scheme; //returns "http/https"
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"
.Host
ので"http://www.foobar.com/Page1"
はwww.foobar.com
なく、foobar.com
です。
リクエストURL文字列全体を取得するには:
HttpContext.Current.Request.Url
リクエストのwww.foo.com部分を取得するには:
HttpContext.Current.Request.Url.Host
ASP.NETアプリケーションの外部の要素のなすがままになっていることに注意してください。IISがアプリケーションの複数または任意のホストヘッダーを受け入れるように構成されている場合、ユーザーが入力したドメインに応じて、DNSを介してアプリケーションに解決されたドメインが要求URLとして表示される場合があります。
Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;
host.com => return host.com
s.host.com => return host.com
host.co.uk => host.co.ukを返す
www.host.co.uk => host.co.ukを
返すs1.www.host.co.uk => host.co.ukを返す
私はこれが古いことを知っていますが、今これを行う正しい方法は
string Domain = HttpContext.Current.Request.Url.Authority
それはサーバーのポートでDNSまたはIPアドレスを取得します。
これも機能します:
string url = HttpContext.Request.Url.Authority;
string host = Request.Url.Host;
Regex domainReg = new Regex("([^.]+\\.[^.]+)$");
HttpCookie cookie = new HttpCookie(cookieName, "true");
if (domainReg.IsMatch(host))
{
cookieDomain = domainReg.Match(host).Groups[1].Value;
}
Request
オブジェクトを調べてみるとよいでしょう。