Ottieni l'URL senza querystring


189

Ho un URL come questo:

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

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

Puoi dirmi come posso ottenerlo?

Risposte:


129

Puoi usare 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);

Oppure puoi usare substring

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

EDIT: modifica della prima soluzione per riflettere il suggerimento di brillyfresh nei commenti.


6
url.AbsolutePath restituisce solo la parte del percorso dell'URL (/mypage.aspx); anteponi url.Scheme (http) + Uri.SchemeDelimiter (: //) + url.Authority (www.somesite.com) per l'URL completo che desideri
Ryan

20
Il metodo Uri.GetLeftPart è più semplice come menzionato stackoverflow.com/questions/1188096/…
Edward Wilde,

Il substringmetodo genererà un errore se non c'è una stringa di query. Usa string path = url.Substring(0, url.IndexOf("?") > 0? url.IndexOf("?") : url.Length);invece.
ventre

378

Ecco una soluzione più semplice:

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

Preso in prestito da qui: troncamento della stringa di query e restituzione dell'URL pulito C # ASP.net


17
Versione a una riga:return Request.Url.GetLeftPart(UriPartial.Path);
jp2code,

uri.GetComponent(è un altro metodo fantastico per ottenere parti di un Uri. Fino ad ora non sapevo di questi due!
AaronLS

38

Questa è la mia soluzione:

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

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

2
Mi piace solo per il fatto che puoi usarlo senza un uri completo.
KingOfHypocrites,

Tieni presente che RawUrlriceverà l'URL prima della riscrittura dell'URL, quindi forse lo usi AbsoluteUri? Request.Url.AbsoluteUri.Split('?')[0]
Protettore uno


16

A modo mio:

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

o

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

Questo è quello che uso per il progetto NET Core 1.0 perché non ha un metodo Uri.GetLeftPart. L'ultima versione di NET Core (1.1) dovrebbe avere quel metodo (non posso confermare perché non sono su Net Core 1.1 per ora)
psulek

1
Mi piace questo perché costruire URI è esattamente ciò che serve a UriBuilder. Tutte le altre risposte sono (buoni) hack.
Nove code

11

È possibile utilizzare Request.Url.AbsolutePathper ottenere il nome della pagina e Request.Url.Authorityper il nome host e la porta. Non credo che ci sia una proprietà integrata per darti esattamente quello che vuoi, ma puoi combinarli da solo.


1
Mi sta dando /mypage.aspx, non quello che volevo.
Rocky Singh,

4

Variazione Split ()

Voglio solo aggiungere questa variazione per riferimento. Gli URL sono spesso stringhe ed è quindi più semplice utilizzare il Split()metodo di Uri.GetLeftPart(). E Split()può anche essere fatto funzionare con valori relativi, vuoti e null mentre Uri genera un'eccezione. Inoltre, gli URL possono contenere anche un hash come /report.pdf#page=10(che apre il pdf in una pagina specifica).

Il seguente metodo si occupa di tutti questi tipi di URL:

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

Esempio di output:


1
Sono piuttosto scioccato che questo non abbia ottenuto alcun voto fino al mio. Questa è un'ottima soluzione
Jason,

3

Ecco un metodo di estensione che utilizza la risposta di @ Kolman. È leggermente più facile ricordare di usare Path () di GetLeftPart. Potresti voler rinominare Path in GetPath, almeno fino a quando non aggiungono le proprietà dell'estensione a C #.

Uso:

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

La classe:

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, hai appena specificato i componenti che desideri.

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

Produzione:

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


0

Soluzione per Silverlight:

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

0

Ho creato una semplice estensione, poiché alcune delle altre risposte hanno generato eccezioni nulle se non ci fosse un QueryStringinizio con:

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;
}

Uso:

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

-1

semplice esempio sarebbe usare la sottostringa come:

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();


Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.