[英]Get URL parameters from a string in .NET
我在 .NET 中有一個字符串,它實際上是一個 URL。我想要一種從特定參數獲取值的簡單方法。
通常,我只會使用Request.Params["theThingIWant"]
,但這個字符串不是來自請求。 我可以像這樣創建一個新的Uri
項目:
Uri myUri = new Uri(TheStringUrlIWantMyValueFrom);
我可以使用myUri.Query
來獲取查詢字符串......但顯然我必須找到一些正則表達式來拆分它。
我是否遺漏了一些明顯的東西,或者除了創建某種正則表達式等之外沒有內置的方法來做到這一點?
使用返回NameValueCollection
的System.Web.HttpUtility
class 的 static ParseQueryString
方法。
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");
這可能是你想要的
var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
var query = HttpUtility.ParseQueryString(uri.Query);
var var2 = query.Get("var2");
如果出於某種原因您不能或不想使用HttpUtility.ParseQueryString()
,這是另一種選擇。
這是為了在一定程度上容忍“格式錯誤”的查詢字符串,即http://test/test.html?empty=
成為具有空值的參數。 如果需要,調用者可以驗證參數。
public static class UriHelper
{
public static Dictionary<string, string> DecodeQueryParameters(this Uri uri)
{
if (uri == null)
throw new ArgumentNullException("uri");
if (uri.Query.Length == 0)
return new Dictionary<string, string>();
return uri.Query.TrimStart('?')
.Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(parameter => parameter.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
.GroupBy(parts => parts[0],
parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
.ToDictionary(grouping => grouping.Key,
grouping => string.Join(",", grouping));
}
}
測試
[TestClass]
public class UriHelperTest
{
[TestMethod]
public void DecodeQueryParameters()
{
DecodeQueryParametersTest("http://test/test.html", new Dictionary<string, string>());
DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>());
DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary<string, string> { { "key", "bla/blub.xml" } });
DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } });
DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary<string, string> { { "empty", "" } });
DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary<string, string> { { "empty", "" } });
DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary<string, string> { { "key", "1" } });
DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } });
DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary<string, string> { { "key", "value=what" } });
DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22",
new Dictionary<string, string>
{
{ "q", "energy+edge" },
{ "rls", "com.microsoft:en-au" },
{ "ie", "UTF-8" },
{ "oe", "UTF-8" },
{ "startIndex", "" },
{ "startPage", "1%22" },
});
DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue", new Dictionary<string, string> { { "key", "value,anotherValue" } });
}
private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected)
{
Dictionary<string, string> parameters = new Uri(uri).DecodeQueryParameters();
Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri);
foreach (var key in expected.Keys)
{
Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri);
Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri);
}
}
}
看起來您應該遍歷myUri.Query
的值並從那里解析它。
string desiredValue;
foreach(string item in myUri.Query.Split('&'))
{
string[] parts = item.Replace("?", "").Split('=');
if(parts[0] == "desiredKey")
{
desiredValue = parts[1];
break;
}
}
但是,如果不對一堆格式錯誤的 URL 進行測試,我不會使用此代碼。 它可能會在某些/所有這些上中斷:
hello.html?
hello.html?valuelesskey
hello.html?key=value=hi
hello.html?hi=value?&b=c
@Andrew 和 @CZFox
我有同樣的錯誤,發現原因是參數一實際上是: http://www.example.com?param1
而不是param1
,這是人們所期望的。
通過刪除之前的所有字符並包括問號可以解決此問題。 所以本質上HttpUtility.ParseQueryString
function 只需要一個有效的查詢字符串參數,該參數只包含問號后的字符,如下所示:
HttpUtility.ParseQueryString ( "param1=good¶m2=bad" )
我的解決方法:
string RawUrl = "http://www.example.com?param1=good¶m2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );
Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`
您可以只使用Uri來獲取查詢字符串列表或查找特定參數。
Uri myUri = new Uri("http://www.example.com?param1=good¶m2=bad");
var params = myUri.ParseQueryString();
var specific = myUri.ParseQueryString().Get("spesific");
var paramByIndex = = myUri.ParseQueryString().Get(1);
您可以從這里找到更多信息: https://docs.microsoft.com/en-us/dotnet/api/system.uri?view=net-5.0
您也可以使用以下解決方法使其與第一個參數一起使用:
var param1 =
HttpUtility.ParseQueryString(url.Substring(
new []{0, url.IndexOf('?')}.Max()
)).Get("param1");
或者如果您不知道 URL(為了避免硬編碼,請使用AbsoluteUri
例子...
//get the full URL
Uri myUri = new Uri(Request.Url.AbsoluteUri);
//get any parameters
string strStatus = HttpUtility.ParseQueryString(myUri.Query).Get("status");
string strMsg = HttpUtility.ParseQueryString(myUri.Query).Get("message");
switch (strStatus.ToUpper())
{
case "OK":
webMessageBox.Show("EMAILS SENT!");
break;
case "ER":
webMessageBox.Show("EMAILS SENT, BUT ... " + strMsg);
break;
}
使用 .NET Reflector 查看System.Web.HttpValueCollection
的FillFromString
方法。 這為您提供了 ASP.NET 用於填充Request.QueryString
集合的代碼。
單線LINQ解決方案:
Dictionary<string, string> ParseQueryString(string query)
{
return query.Replace("?", "").Split('&').ToDictionary(pair => pair.Split('=').First(), pair => pair.Split('=').Last());
}
如果您想在默認頁面上獲取 QueryString。默認頁面表示您的當前頁面 url。 你可以試試這段代碼:
string paramIl = HttpUtility.ParseQueryString(this.ClientQueryString).Get("city");
這實際上非常簡單,對我有用:)
if (id == "DK")
{
string longurl = "selectServer.aspx?country=";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["country"] = "DK";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
}
對於任何想要遍歷字符串中的所有查詢字符串的人
foreach (var item in new Uri(urlString).Query.TrimStart('?').Split('&'))
{
var subStrings = item.Split('=');
var key = subStrings[0];
var value = subStrings[1];
// do something with values
}
如何獲得知道參數名稱的值的最簡單方法:
using System.Linq;
string loc = "https://localhost:5000/path?desiredparam=that_value&anotherParam=whatever";
var c = loc.Split("desiredparam=").Last().Split("&").First();//that_value
這是一個示例,其中提到了 dll 要包含的內容
var testUrl = "https://www.google.com/?q=foo";
var data = new Uri(testUrl);
// Add a reference to System.Web.dll
var args = System.Web.HttpUtility.ParseQueryString(data.Query);
args.Set("q", "my search term");
var nextUrl = $"{data.Scheme}://{data.Host}{data.LocalPath}?{args.ToString()}";
HttpContext.Current.Request.QueryString.Get("id");
我用了它,它運行得很好
<%=Request.QueryString["id"] %>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.