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?
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:
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.
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.
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
return Request.Url.GetLeftPart(UriPartial.Path);
uri.GetComponent(è un altro metodo fantastico per ottenere parti di un Uri. Fino ad ora non sapevo di questi due!
Request.RawUrl.Split(new[] {'?'})[0];
RawUrlriceverà l'URL prima della riscrittura dell'URL, quindi forse lo usi AbsoluteUri? Request.Url.AbsoluteUri.Split('?')[0]
Buona risposta trovato anche qui fonte di risposta
Request.Url.GetLeftPart(UriPartial.Path)
A modo mio:
new UriBuilder(url) { Query = string.Empty }.ToString()
o
new UriBuilder(url) { Query = string.Empty }.Uri
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)
È 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.
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:
http: //domain/page.html#page=2 ---> http: //domain/page.html
page.html ---> page.html
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¶m2=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);
}
}
}
string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.split('?')[0];
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
Request.RawUrl.Split('?')[0]
Solo per nome url !!
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()
var canonicallink = Request.Url.Scheme + "://" + Request.Url.Authority + Request.Url.AbsolutePath.ToString();
Prova questo:
urlString=Request.RawUrl.ToString.Substring(0, Request.RawUrl.ToString.IndexOf("?"))
da questo: http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye otterrai questo: mypage.aspx
this.Request.RawUrl.Substring(0, this.Request.RawUrl.IndexOf('?'))