解析和修改.NET核心查询字符串 [英] Parse and modify a query string in .NET Core
问题描述
我给出一个绝对URI包含查询字符串。我期待能够安全地追加值的查询字符串,并改变现有的参数。
I am given an absolute URI that contains a query string. I'm looking to safely append a value to the query string, and change an existing parameter.
我想preFER不要钉在&安培;富=栏
,或使用常规的前pressions,URI转义是棘手的。而我想用一个内置的机制,我知道会正确地做到这一点,处理转义。
I would prefer not to tack on &foo=bar
, or use regular expressions, URI escaping is tricky. Rather I want to use a built-in mechanism that I know will do this correctly and handle the escaping.
我发现的一 <一个href=\"http://stackoverflow.com/questions/11956948/easiest-way-to-parse-querystring-formatted-data\">ton答案是全部使用 HttpUtility
。然而,这是ASP.NET的核心,没有更多的System.Web程序集了,所以没有更多的 HttpUtility
。
I've found a ton of answers that all use HttpUtility
. However this being ASP.NET Core, there is no more System.Web assembly anymore, thus no more HttpUtility
.
什么是适当的方式在ASP.NET核心,而针对核心运行时做到这一点?
What is the appropriate way to do this in ASP.NET Core while targeting the core runtime?
推荐答案
我想通了,你可以在 Microsoft.AspNet.WebUtilities.QueryHelpers
这样做的<一个href=\"https://www.nuget.org/packages/Microsoft.AspNet.WebUtilities/\">Microsoft.AspNet.WebUtilities包。
I figured out you can do this with Microsoft.AspNet.WebUtilities.QueryHelpers
in the Microsoft.AspNet.WebUtilities package.
要解析成一个字典:
var uri = new Uri(context.RedirectUri);
var queryDictionary = Microsoft.AspNet.WebUtilities.QueryHelpers.ParseQuery(uri.Query);
请注意,不像 ParseQueryString
的System.Web中,这将返回类型的字典的IDictionary&LT;字符串,字符串[]&GT;
,所以该值是一个字符串数组。这是字典如何处理多个查询字符串参数具有相同的名称。
Note that unlike ParseQueryString
in System.Web, this returns a dictionary of type IDictionary<string, string[]>
, so the value is an array of strings. This is how the dictionary handles multiple query string parameters with the same name.
如果你想上查询字符串添加参数,您可以使用另一种方法 QueryHelpers
:
If you want to add a parameter on to the query string, you can use another method on QueryHelpers
:
var parametersToAdd = new System.Collections.Generic.Dictionary<string, string> { { "resource", "foo" } };
var someUrl = "http://www.google.com";
var newUri = Microsoft.AspNet.WebUtilities.QueryHelpers.AddQueryString(someUrl, parametersToAdd);
这篇关于解析和修改.NET核心查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!