【发布时间】:2017-06-25 22:50:31
【问题描述】:
可以使用System.Uri.Compare 比较两个 URI。
然而,比较http://example.com/pages?pageStart=100&pageSize=50 和http://example.com/pages?pageSize=50&pageStart=100 表明这两个URI 是不同的。有什么方法可以让比较忽略查询字符串中值出现的顺序;因为这两个 URI 在功能上是相同的。
我正在考虑编写一个包装器方法来在调用标准比较函数之前按顺序排列查询字符串参数,但想先检查是否有现成的解决方案,因为比较似乎很奇怪还没有这个选项。
更新
这是我提出的用于比较两个 URI 的解决方案,无论它们的查询字符串参数顺序如何。如上所述,这是通过首先对每个 URI 的查询字符串进行排序来实现的。但是,如果 .net 中有现有的解决方案,我宁愿放弃我的代码并使用它。
function CompareUri ($GivenUri, $ShouldBeUri) {
$uriComponentsOptions = ([UriComponents]::AbsoluteUri)
$uriFormatOptions = ([UriFormat]::SafeUnescaped)
$stringComparisonOptions = ([StringComparison]::OrdinalIgnoreCase)
$a = OrderUriQueryString($GivenUri)
$b = OrderUriQueryString($ShouldBeUri)
[Uri]::Compare($a, $b, $uriComponentsOptions, $uriFormatOptions, $stringComparisonOptions)
}
function OrderUriQueryString($Uri) {
[System.UriBuilder]$UriBuilder = New-Object -TypeName 'System.UriBuilder' -ArgumentList $Uri
[System.Collections.Specialized.NameValueCollection]$Query = [System.Web.HttpUtility]::ParseQueryString($UriBuilder.Query)
[System.Collections.Specialized.NameValueCollection]$Query2 = [System.Web.HttpUtility]::ParseQueryString('') #we have to initialise this way as HttpValueCollection has no public constructor (https://referencesource.microsoft.com/#system.web/HttpValueCollection.cs,fde6b9ec5f1ed58a,references)
$Query.AllKeys | sort | %{ $Query2.Add($_, $Query[$_]) }
$UriBuilder.Query = $Query2.ToString()
$UriBuilder.ToString()
}
【问题讨论】:
标签: c# .net powershell uri query-string