Program Tip

ASP.NET에서 현재 도메인 이름을 얻는 방법

programtip 2020. 11. 22. 20:26
반응형

ASP.NET에서 현재 도메인 이름을 얻는 방법


asp.net c #에서 현재 도메인 이름을 얻고 싶습니다.

이 코드를 사용하고 있습니다.

string DomainName = HttpContext.Current.Request.Url.Host;

내 URL은 localhost:5858있지만 localhost.

이제 localhost에서 내 프로젝트를 사용하고 있습니다. 나는 localhost : 5858을 얻고 싶다.

다른 예를 들어,이 도메인을 사용할 때

www.somedomainname.com

난 갖길 원해 somedomainname.com

현재 도메인 이름을 얻는 방법을 알려주세요.


사용 Request.Url.Host이 적절 Host:합니다. HTTP 요청의 리소스 경로 부분에 호스트 이름이 포함되지 않으므로 UA (브라우저)가 원하는 호스트 이름 (도메인 이름)을 지정하는 HTTP 헤더 값을 검색하는 방법 입니다.

참고 localhost:5858도메인 이름이 아닌, 또한 호스트 이름과 TCP 포트 번호를 포함하는 "권위"로 알려진 엔드 포인트 지정자입니다. 이것은에 액세스하여 검색됩니다 Request.Uri.Authority.

또한와 비교하여 다른 사이트를 제공하도록 웹 서버를 구성 할 수 있기 때문에 에서 가져 somedomain.com오는 것은 유효하지 않습니다 . 그러나 이것이 유효한 경우라면 호스트 이름을 수동으로 구문 분석해야 합니다. 꼬집음.www.somedomain.comwww.somedomain.comsomedomain.comString.Split('.')

웹 서버 (IIS) 구성은 ASP.NET의 구성과 다르며 ASP.NET은 실제로 실행되는 웹 사이트 및 웹 응용 프로그램의 HTTP 바인딩 구성을 완전히 무시합니다. IIS와 ASP.NET이 동일한 구성 파일 ( web.config)을 공유한다는 사실은 위험합니다.


다음과 같이 URL의 "왼쪽 부분"을 가져 오십시오.

string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);

이 중 하나를 줄 것이다 http://localhost:5858또는 https://www.somedomainname.com로컬 또는 생산에있어 여부. www부분 을 삭제하려면 IIS를 구성해야하지만 이는 또 다른 주제입니다.

결과 URL에는 후행 슬래시가 없습니다.


다음은 Request.RequestUri모든 사람이 참조 할 수있는 모든 속성 의 스크린 샷입니다 .

여기에 이미지 설명 입력


다음 코드를 시도해 볼 수 있습니다.

 Request.Url.Host +
    (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)

www.somedomain.com 이다 도메인 / 호스트. 하위 도메인은 중요한 부분입니다. www.는 자주 사용하지 않는 것과 같은 의미로 사용되지만 동일하지 않기 때문에 규칙으로 설정해야합니다 (기본적으로 설정되어 있더라도). 같은 다른 하위 도메인을 생각해보십시오 mx.. 그것은 아마도 www..

Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.

Personally, I'd suggest special-casing www. for this.

string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;

if (host.StartsWith("www."))
    return host.Substring(4);
else
    return host;

Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.

string host = ...;

int lastDot = host.LastIndexOf('.');

int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');

if (secondToLastDot > -1)
    return host.Substring(secondToLastDot + 1);
else
    return host;

Getting the port is just like other people have said.


the Request.ServerVariables object works for me. I don't know of any reason not to use it.

ServerVariables["SERVER_NAME"] and ServerVariables["HTTP_URL"] should get what you're looking for


HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use

HttpContext.Current.Request.Url.Port 

You can try the following code to get fully qualified domain name:

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

다음은 URL의 이름을 얻는 빠르고 쉬운 방법입니다.

            var urlHost = HttpContext.Current.Request.Url.Host;

            var xUrlHost = urlHost.Split('.');
            foreach(var thing in xUrlHost)
            {
                if(thing != "www" && thing != "com")
                {
                    urlHost = thing;
                }
            }

하위 도메인이 있어도 MVC에서 기본 URL을 얻으려면 www.somedomain.com/subdomain다음을 수행하십시오.

var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";

이 시도:

@ Request.Url.GetLeftPart (UriPartial.Authority)

참고 URL : https://stackoverflow.com/questions/26189953/how-to-get-current-domain-name-in-asp-net

반응형