ASP에서 가장 좋은 방법은 무엇입니까?현재 도메인을 얻기 위한 NET?
ASP에서 현재 도메인을 얻는 가장 좋은 방법이 무엇인지 궁금합니다.NET?
예를 들어:
http://www.domainname.com/subdir/ 은 http://www.domainname.com 을 양보해야 합니다. http://www.sub.domainname.com/subdir/ 은 http://sub.domainname.com 을 양보해야 합니다.
가이드로서 "/Folder/Content/filename.html"과 같은 URL을 추가할 수 있어야 합니다(Url에서 생성된 것과 동일).ASP의 RouteUrl()입니다.NET MVC) URL로 바로 이동하면 작동합니다.
Matt Mitchell의 답변과 동일하지만 약간의 수정이 있습니다.대신 기본 포트를 확인합니다.
편집: 구문 및 사용 업데이트
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위의 카를로스 무뇨스의 수락된 답변에서와 같이.
Request.Url.GetLeftPart(UriPartial.Authority)
이것은 포함된 계획입니다.
경고! 전류를 사용하는 모든 사람에게.요청합니다.Url.Host.현재 요청에 따라 작업하고 있으며, 현재 요청이 항상 서버에 있는 것은 아니며 다른 서버에 있을 수도 있습니다.
따라서 Global.asax의 Application_BeginRequest()와 같은 경우 99.9%는 괜찮지만 0.1%는 자신의 서버의 호스트 이름이 아닌 다른 이름을 얻을 수 있습니다.
이것의 좋은 예는 제가 얼마 전에 발견한 것입니다.제 서버는 가끔 http://proxyjudge1.proxyfire.net/fastenv 에 접속합니다.Application_BeginRequest()는 요청을 호출하는 경우 이 요청을 기꺼이 처리합니다.Url.Host가 이 요청을 하면 proxyjudge1.proxyfire.net 을 받을 수 있습니다.여러분 중 일부는 "아니오"라고 생각할 수 있지만, 그것은 단지 0.1%의 시간만 발생했기 때문에 알아차리기 매우 어려운 버그였기 때문에 주목할 가치가 있습니다: P.
이 버그로 인해 도메인 호스트를 구성 파일에 문자열로 삽입해야 했습니다.
사용하지 않는 이유
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://example.com:5031
// Example output: http://example.com:5031
다른 방법:
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"];
전체 도메인을 얻으려면 As.Net Core 3.1에서 다음을 수행해야 합니다.
1단계: 변수 정의
private readonly IHttpContextAccessor _contextAccessor;
2단계: 생성자 내부 DI
public SomeClass(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
3단계: 클래스에 이 메서드를 추가합니다.
private string GenerateFullDomain()
{
string domain = _contextAccessor.HttpContext.Request.Host.Value;
string scheme = _contextAccessor.HttpContext.Request.Scheme;
string delimiter = System.Uri.SchemeDelimiter;
string fullDomainToUse = scheme + delimiter + domain;
return fullDomainToUse;
}
//Examples of usage GenerateFullDomain() method:
//https://example.com:5031
//http://example.com:5031
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
언급URL : https://stackoverflow.com/questions/61817/whats-the-best-method-in-asp-net-to-obtain-the-current-domain
'programing' 카테고리의 다른 글
| 푸시되지 않은 GIT 커밋을 삭제하려면 어떻게 해야 합니까? (0) | 2023.04.29 |
|---|---|
| 프로젝트에서 코코아 포드를 제거하는 방법은 무엇입니까? (0) | 2023.04.29 |
| WPF에서 문화를 설정하고 변경하는 방법 (0) | 2023.04.29 |
| arc4random_uniform()의 범위 사이에 난수를 어떻게 만들 수 있습니까? (0) | 2023.04.29 |
| Xcode 10 오류: 여러 명령이 생성됩니다. (0) | 2023.04.29 |