문제

ASP.NET에서 현재 도메인을 얻는 가장 좋은 방법이 무엇인지 궁금합니다.

예를 들어:

http://www.domainname.com/subdir/ 양보해야 한다 http://www.도메인이름.com http://www.sub.domainname.com/subdir/ 양보해야 한다 http://sub.도메인이름.com

참고로 "/Folder/Content/filename.html"(ASP.NET MVC의 Url.RouteUrl()에 의해 생성된 URL)과 같은 URL을 URL에 바로 추가할 수 있어야 작동합니다.

도움이 되었습니까?

해결책

MattMitchell의 답변과 동일하지만 약간 수정되었습니다.대신 기본 포트를 확인합니다.

편집하다:업데이트된 구문 및 사용 Request.Url.Authority 제안대로

$"{Request.Url.Scheme}{System.Uri.SchemeDelimiter}{Request.Url.Authority}"

다른 팁

에 따라 이 링크 좋은 출발점은 다음과 같습니다.

Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host 

그러나 도메인이 다음과 같은 경우 http://www.domainname.com:500 이것은 실패할 것이다.

다음과 같은 방법으로 이 문제를 해결할 수 있습니다.

int defaultPort = Request.IsSecureConnection ? 443 : 80;
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host 
  + (Request.Url.Port != defaultPort ? ":" + Request.Url.Port : "");

그러나 포트 80과 443은 구성에 따라 달라집니다.

따라서 다음을 사용해야 합니다. IsDefaultPort 에서와 같이 수락된 답변 위의 Carlos Muñoz에서.

Request.Url.GetLeftPart(UriPartial.Authority)

이 구성표에 포함되어 있습니다.

경고! 이용하는 누구에게나 현재.요청.Url.호스트.귀하는 현재 요청을 기반으로 작업하고 있으며 현재 요청이 항상 귀하의 서버에 있는 것이 아니며 때로는 다른 서버에 있을 수 있다는 점을 이해하십시오.

따라서 Global.asax의 Application_BeginRequest()와 같은 작업에서 이것을 사용하면 99.9%의 경우 문제가 없지만 0.1%는 자신의 서버 호스트 이름이 아닌 다른 이름을 얻을 수도 있습니다.

이에 대한 좋은 예는 제가 얼마 전에 발견한 것입니다.내 서버가 공격을 받는 경향이 있습니다. http://proxyjudge1.proxyfire.net/fastenv 때때로.Application_BeginRequest()는 이 요청을 기꺼이 처리하므로 이 요청을 할 때 Request.Url.Host를 호출하면 Proxyjudge1.proxyfire.net을 다시 받게 됩니다.여러분 중 일부는 "안돼"라고 생각할 수도 있지만 이 버그는 0.1%의 경우에만 발생했기 때문에 알아차리기 매우 어려운 버그였기 때문에 주목할 가치가 있습니다.피

이 버그로 인해 내 도메인 호스트를 구성 파일에 문자열로 삽입해야 했습니다.

왜 사용하지 않습니까?

Request.Url.Authority

전체 도메인과 포트를 반환합니다.

여전히 http 또는 https를 알아야 합니다.

단순한 그리고 짧은 방식(스키마, 도메인 및 포트 지원):

사용 Request.GetFullDomain()

// Add this class to your project
public static class HttpRequestExtensions{
    public static string GetFullDomain(this HttpRequestBase request)
    {
        var uri= request?.UrlReferrer;
        if (uri== null)
            return string.Empty;
        return uri.Scheme + Uri.SchemeDelimiter + uri.Authority;
    }
}

// Now Use it like this:
Request.GetFullDomain();
// Example output:    https://www.example.com:5031
// Example output:    http://www.example.com:5031
// Example output:    https://www.example.com

또 다른 방법:


string domain;
Uri url = HttpContext.Current.Request.Url;
domain= url.AbsoluteUri.Replace(url.PathAndQuery, string.Empty);

어떻습니까:

NameValueCollection vars = HttpContext.Current.Request.ServerVariables;
string protocol = vars["SERVER_PORT_SECURE"] == "1" ? "https://" : "http://";
string domain = vars["SERVER_NAME"];
string port = vars["SERVER_PORT"];

UriBuilder 사용:

    var relativePath = ""; // or whatever-path-you-want
    var uriBuilder = new UriBuilder
    {
        Host = Request.Url.Host,
        Path = relativePath,
        Scheme = Request.Url.Scheme
    };

    if (!Request.Url.IsDefaultPort)
        uriBuilder.Port = Request.Url.Port;

    var fullPathToUse = uriBuilder.ToString();

어떻습니까:

String domain = "http://" + Request.Url.Host
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top