검색어없이 URL을 가져옵니다.


189

다음과 같은 URL이 있습니다.

http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye

나는 http://www.example.com/mypage.aspx그것을 얻고 싶다 .

어떻게 구할 수 있는지 말씀해 주시겠습니까?

답변:


129

당신이 사용할 수있는 System.Uri

Uri url = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = String.Format("{0}{1}{2}{3}", url.Scheme, 
    Uri.SchemeDelimiter, url.Authority, url.AbsolutePath);

아니면 사용할 수 있습니다 substring

string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.Substring(0, url.IndexOf("?"));

편집 : 의견에 brillyfresh의 제안을 반영하도록 첫 번째 솔루션 수정.


6
url.AbsolutePath는 URL의 경로 부분 만 반환합니다 (/mypage.aspx). 원하는 전체 URL 앞에 url.Scheme (http) + Uri.SchemeDelimiter (: //) + url.Authority (www.somesite.com)
Ryan

20
Uri.GetLeftPart 방법은 언급 한 바와 같이 간단 stackoverflow.com/questions/1188096/...
에드워드 와일드

substring에는 쿼리 문자열이 존재하지 않는 경우는 방법은 오류를 줄 것이다. string path = url.Substring(0, url.IndexOf("?") > 0? url.IndexOf("?") : url.Length);대신 사용하십시오 .
stomy

378

더 간단한 해결책은 다음과 같습니다.

var uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = uri.GetLeftPart(UriPartial.Path);

여기에서 빌린 : 쿼리 문자열 자르기 및 깨끗한 URL 반환 C # ASP.net


17
한 줄 버전 :return Request.Url.GetLeftPart(UriPartial.Path);
jp2code

uri.GetComponent(Uri의 일부를 얻는 또 다른 멋진 방법입니다. 나는 지금까지이 둘에 대해 몰랐다!
AaronLS

38

이것은 내 솔루션입니다.

Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty);

35
Request.RawUrl.Split(new[] {'?'})[0];

2
나는 당신이 완전한 uri없이 그것을 사용할 수 있다는 사실 때문에 이것을 좋아합니다.
KingOfHypocrites

명심 RawUrlURL을 얻을 것이다 전에 그래서 아마도 사용, URL 재 작성을 AbsoluteUri? Request.Url.AbsoluteUri.Split('?')[0]
수호자 1


16

내 길 :

new UriBuilder(url) { Query = string.Empty }.ToString()

또는

new UriBuilder(url) { Query = string.Empty }.Uri

이 방법이 없기 때문에 NET Core 1.0 프로젝트에 사용하는 것 Uri.GetLeftPart입니다. NET Core (1.1)의 최신 버전은 그 방법을 가져야합니다 (현재로서는 net core 1.1이 아니기 때문에 확인할 수 없습니다)
psulek

1
URI를 빌드하는 것이 UriBuilder를위한 것이기 때문에 이것을 좋아합니다. 다른 모든 답변은 (좋은) 해킹입니다.
9 꼬리 17시

11

Request.Url.AbsolutePath페이지 이름과 Request.Url.Authority호스트 이름 및 포트 를 얻는 데 사용할 수 있습니다 . 나는 당신이 원하는 것을 정확하게 줄 수있는 빌트인 속성이 있다고 생각하지 않지만 직접 결합 할 수 있습니다.


1
내가 원하는 것이 아닌 /mypage.aspx을 제공합니다.
Rocky Singh

4

Split () 변형

참고로이 변형을 추가하고 싶습니다. URL은 종종 문자열이므로 Split()보다 방법 을 사용하는 것이 더 간단합니다 Uri.GetLeftPart(). 그리고 Split()Uri는 예외를 던지는 반면 상대, 빈 및 null 값으로 작동하도록 만들 수도 있습니다. 또한 Urls에는 /report.pdf#page=10(해당 페이지에서 pdf를 여는) 해시가 포함될 수도 있습니다 .

다음 방법은 이러한 모든 유형의 Urls를 처리합니다.

   var path = (url ?? "").Split('?', '#')[0];

출력 예 :


1
나는 이것이 내 자신의 때까지 어떤 upvotes도 얻지 못했다는 것에 충격을 받았다. 이것은 훌륭한 솔루션입니다.
Jason Jason

3

@Kolman의 답변을 사용하는 확장 방법이 있습니다. GetLeftPart보다 Path ()를 사용하는 것이 조금 더 쉽습니다. 적어도 C #에 확장 속성을 추가 할 때까지 Path의 경로를 GetPath로 바꾸는 것이 좋습니다.

용법:

Uri uri = new Uri("http://www.somewhere.com?param1=foo&param2=bar");
string path = uri.Path();

클래스:

using System;

namespace YourProject.Extensions
{
    public static class UriExtensions
    {
        public static string Path(this Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            return uri.GetLeftPart(UriPartial.Path);
        }
    }
}

1
    string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
    string path = url.split('?')[0];

1

System.Uri.GetComponents원하는 구성 요소 만 지정했습니다.

Uri uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);

산출:

http://www.example.com/mypage.aspx


0

Silverlight 솔루션 :

string path = HtmlPage.Document.DocumentUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);

0

다른 답변 중 몇 가지 QueryString로 시작 하지 않으면 null 예외가 발생했기 때문에 간단한 확장을 만들었습니다 .

public static string TrimQueryString(this string source)
{ 
    if (string.IsNullOrEmpty(source))
            return source;

    var hasQueryString = source.IndexOf('?') != -1;

    if (!hasQueryString)
        return source;

    var result = source.Substring(0, source.IndexOf('?'));

    return result;
}

용법:

var url = Request.Url?.AbsoluteUri.TrimQueryString() 

-1

간단한 예는 다음과 같은 하위 문자열을 사용하는 것입니다.

string your_url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path_you_want = your_url .Substring(0, your_url .IndexOf("?"));

-1
var canonicallink = Request.Url.Scheme + "://" + Request.Url.Authority + Request.Url.AbsolutePath.ToString();


당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.