在 .NET Core 中解析和修改查询字符串 [英] 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.
我不想添加 &foo=bar
,或者使用正则表达式,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.
我找到 a 大量全部使用 HttpUtility
.然而,这是 ASP.NET Core,不再有 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 Core 中针对核心运行时执行此操作的适当方法是什么?
What is the appropriate way to do this in ASP.NET Core while targeting the core runtime?
推荐答案
如果您使用的是 ASP.NET Core 1 或 2,您可以使用 Microsoft.AspNetCore.WebUtilities.QueryHelpers
在Microsoft.AspNetCore.WebUtilities 包.
If you are using ASP.NET Core 1 or 2, you can do this with Microsoft.AspNetCore.WebUtilities.QueryHelpers
in the Microsoft.AspNetCore.WebUtilities package.
如果您使用的是 ASP.NET Core 3.0 或更高版本,WebUtilities
现在是 ASP.NET SDK 的一部分,不需要单独的 nuget 包引用.
If you are using ASP.NET Core 3.0 or greater, WebUtilities
is now part of the ASP.NET SDK and does not require a separate nuget package reference.
将其解析为字典:
var uri = new Uri(context.RedirectUri);
var queryDictionary = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query);
请注意,与 System.Web 中的 ParseQueryString
不同,它返回 ASP.NET Core 1.x 中 IDictionary
类型的字典,或 IDictionary
在 ASP.NET Core 2.x 或更高版本中,因此该值是字符串的集合.这就是字典处理多个同名查询字符串参数的方式.
Note that unlike ParseQueryString
in System.Web, this returns a dictionary of type IDictionary<string, string[]>
in ASP.NET Core 1.x, or IDictionary<string, StringValues>
in ASP.NET Core 2.x or greater, so the value is a collection 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.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(someUrl, parametersToAdd);
使用 .net core 2.2,您可以使用
Using .net core 2.2 you can get the query string using
var request = HttpContext.Request;
var query = request.Query;
foreach (var item in query){
Debug.WriteLine(item)
}
你会得到一组键值对——就像这样
You will get a collection of key:value pairs - like this
[0] {[companyName, ]}
[1] {[shop, ]}
[2] {[breath, ]}
[3] {[hand, ]}
[4] {[eye, ]}
[5] {[firstAid, ]}
[6] {[eyeCleaner, ]}
这篇关于在 .NET Core 中解析和修改查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!