Jak przetworzyć łańcuch zapytania do NameValueCollection in.NET
Chciałbym przetworzyć łańcuch taki jak p1=6&p2=7&p3=8
do NameValueCollection
.
Jaki jest najbardziej elegancki sposób na zrobienie tego, gdy nie masz dostępu do obiektu Page.Request
?
18 answers
Do tego jest wbudowane narzędzie. NET: HttpUtility.ParseQueryString
// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
Może być konieczne zastąpienie querystring
przez new Uri(fullUrl).Query
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-30 13:11:35
HttpUtility.ParseQueryString będzie działać tak długo, jak jesteś w aplikacji internetowej lub nie przeszkadza w tym zależności od systemu.Www. Innym sposobem na to jest:
NameValueCollection queryParameters = new NameValueCollection();
string[] querySegments = queryString.Split('&');
foreach(string segment in querySegments)
{
string[] parts = segment.Split('=');
if (parts.Length > 0)
{
string key = parts[0].Trim(new char[] { '?', ' ' });
string val = parts[1].Trim();
queryParameters.Add(key, val);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-16 02:10:24
Wiele odpowiedzi dostarcza niestandardowych przykładów ze względu na zależność przyjętej odpowiedzi od systemu .Web . Z Microsoftu.AspNet.WebApi.Klient pakiet NuGet istnieje UriExtensions.ParseQueryString , metoda, która może być również użyta:
var uri = new Uri("https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8");
NameValueCollection query = uri.ParseQueryString();
Więc jeśli chcesz uniknąć Systemu.Web zależność i nie chcesz zwijać własnej, jest to dobra opcja.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-18 21:19:47
Chciałem usunąć zależność od systemu.Web, aby móc analizować ciąg zapytań wdrożenia ClickOnce, mając wymagania wstępne ograniczone do "podzbioru frameworku tylko dla klientów".
Podobała mi się odpowiedź rp. Dodałem trochę dodatkowej logiki.
public static NameValueCollection ParseQueryString(string s)
{
NameValueCollection nvc = new NameValueCollection();
// remove anything other than query string from url
if(s.Contains("?"))
{
s = s.Substring(s.IndexOf('?') + 1);
}
foreach (string vp in Regex.Split(s, "&"))
{
string[] singlePair = Regex.Split(vp, "=");
if (singlePair.Length == 2)
{
nvc.Add(singlePair[0], singlePair[1]);
}
else
{
// only one key with no value specified in query string
nvc.Add(singlePair[0], string.Empty);
}
}
return nvc;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-08-24 15:08:27
Potrzebowałem funkcji, która jest nieco bardziej wszechstronna niż ta, którą dostarczano już podczas pracy z zapytaniami OLSC.
- wartości mogą zawierać wiele znaków równości
- dekodowanie zakodowanych znaków w nazwie i wartości
- Możliwość pracy na frameworku klienta
- zdolny do pracy na frameworku mobilnym.
Oto moje rozwiązanie:
Public Shared Function ParseQueryString(ByVal uri As Uri) As System.Collections.Specialized.NameValueCollection
Dim result = New System.Collections.Specialized.NameValueCollection(4)
Dim query = uri.Query
If Not String.IsNullOrEmpty(query) Then
Dim pairs = query.Substring(1).Split("&"c)
For Each pair In pairs
Dim parts = pair.Split({"="c}, 2)
Dim name = System.Uri.UnescapeDataString(parts(0))
Dim value = If(parts.Length = 1, String.Empty,
System.Uri.UnescapeDataString(parts(1)))
result.Add(name, value)
Next
End If
Return result
End Function
Nie jest to zły pomysł, aby również na tym zaznaczyć <Extension()>
, aby dodać możliwość do samego Uri.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-15 12:57:08
Aby zrobić to bez System.Web
, bez pisania tego samodzielnie i bez dodatkowych pakietów NuGet:
- Dodaj odniesienie do
System.Net.Http.Formatting
- dodaj
using System.Net.Http;
-
Użyj tego kodu:
new Uri(uri).ParseQueryString()
Https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs. 118).aspx
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-01 17:46:42
private void button1_Click( object sender, EventArgs e )
{
string s = @"p1=6&p2=7&p3=8";
NameValueCollection nvc = new NameValueCollection();
foreach ( string vp in Regex.Split( s, "&" ) )
{
string[] singlePair = Regex.Split( vp, "=" );
if ( singlePair.Length == 2 )
{
nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-16 02:00:02
Właśnie zdałem sobie sprawę, że Klient Web API ma metodę rozszerzenia ParseQueryString
, która działa na Uri
i zwraca HttpValueCollection
:
var parameters = uri.ParseQueryString();
string foo = parameters["foo"];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-23 21:28:43
Just access Request.QueryString. AllKeys wymienione jako inna odpowiedź po prostu dostaje tablicę kluczy.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-16 01:46:27
HttpUtility.ParseQueryString(Request.Url.Query)
return is HttpValueCollection
(klasa wewnętrzna). Dziedziczy od NameValueCollection
.
var qs = HttpUtility.ParseQueryString(Request.Url.Query);
qs.Remove("foo");
string url = "~/Default.aspx";
if (qs.Count > 0)
url = url + "?" + qs.ToString();
Response.Redirect(url);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-08 17:29:36
Jeśli nie chcesz systemu.Zależność od sieci, po prostu wklej ten kod źródłowy z klasy HttpUtility.
Właśnie zebrałem to z kodu źródłowego Mono . Zawiera HttpUtility i wszystkie jego zależności (jak IHtmlString, Helpers, HttpEncoder, HttpQSCollection).
Następnie użyj HttpUtility.ParseQueryString
.
Https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c
Ponieważ wszyscy wydają się wklejać jego rozwiązanie.. oto mój :-)
Potrzebowałem tego z biblioteki klas Bez System.Web
, Aby pobrać parametry id z przechowywanych hiperłączy.
Pomyślałem, że się podzielę, ponieważ znajduję to rozwiązanie szybciej i lepiej wyglądające.
public static class Statics
public static Dictionary<string, string> QueryParse(string url)
{
Dictionary<string, string> qDict = new Dictionary<string, string>();
foreach (string qPair in url.Substring(url.IndexOf('?') + 1).Split('&'))
{
string[] qVal = qPair.Split('=');
qDict.Add(qVal[0], Uri.UnescapeDataString(qVal[1]));
}
return qDict;
}
public static string QueryGet(string url, string param)
{
var qDict = QueryParse(url);
return qDict[param];
}
}
Użycie:
Statics.QueryGet(url, "id")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-01 20:24:17
Jeśli chcesz uniknąć zależności od systemu.Www, która jest wymagana do użycia HttpUtility.ParseQueryString, można użyć metody rozszerzenia Uri
ParseQueryString
znalezionej w System.Net.Http
.
Upewnij się, że dodałeś referencję (jeśli jeszcze tego nie zrobiłeś) do System.Net.Http
w swoim projekcie.
Zauważ, że musisz przekonwertować ciało odpowiedzi na poprawne Uri
tak, aby ParseQueryString
(w System.Net.Http
)działało.
string body = "value1=randomvalue1&value2=randomValue2";
// "http://localhost/query?" is added to the string "body" in order to create a valid Uri.
string urlBody = "http://localhost/query?" + body;
NameValueCollection coll = new Uri(urlBody).ParseQueryString();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-16 14:37:49
Hit up Request.QueryString.Klucze do NameValueCollection wszystkich parametrów ciągu zapytania.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-16 01:45:40
Aby uzyskać wszystkie wartości Querystring, spróbuj tego:
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
Dim sb As New StringBuilder("<br />")
For Each s As String In qscoll.AllKeys
Response.Write(s & " - " & qscoll(s) & "<br />")
Next s
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-24 10:36:23
var q = Request.QueryString;
NameValueCollection qscoll = HttpUtility.ParseQueryString(q.ToString());
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-21 09:42:04
I translate to C# version of josh-brown in VB
private System.Collections.Specialized.NameValueCollection ParseQueryString(Uri uri)
{
var result = new System.Collections.Specialized.NameValueCollection(4);
var query = uri.Query;
if (!String.IsNullOrEmpty(query))
{
var pairs = query.Substring(1).Split("&".ToCharArray());
foreach (var pair in pairs)
{
var parts = pair.Split("=".ToCharArray(), 2);
var name = System.Uri.UnescapeDataString(parts[0]);
var value = (parts.Length == 1) ? String.Empty : System.Uri.UnescapeDataString(parts[1]);
result.Add(name, value);
}
}
return result;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-06 10:37:14
To jest mój kod, myślę, że jest bardzo przydatny:
public String GetQueryString(string ItemToRemoveOrInsert = null, string InsertValue = null )
{
System.Collections.Specialized.NameValueCollection filtered = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (ItemToRemoveOrInsert != null)
{
filtered.Remove(ItemToRemoveOrInsert);
if (!string.IsNullOrWhiteSpace(InsertValue))
{
filtered.Add(ItemToRemoveOrInsert, InsertValue);
}
}
string StrQr = string.Join("&", filtered.AllKeys.Select(key => key + "=" + filtered[key]).ToArray());
if (!string.IsNullOrWhiteSpace(StrQr)){
StrQr="?" + StrQr;
}
return StrQr;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-10 19:27:13