NameValueCollection 转换为 Json

本文介绍了如何将NameValueCollection转换为Json字符串,包括创建扩展方法简化转换过程,并处理NameValueCollection中一个键可能对应多个值的情况。通过序列化字典,可以将NameValueCollection转换成Json,当键有多个值时,转换结果会以数组形式表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参阅:http://stackoverflow.com/questions/7003740/how-to-convert-namevaluecollection-to-json-string

thenvc.AllKeys.ToDictionary(k => k, k => thenvc[k]);

If you need to do the conversion frequently, you can also create an extension method to NameValueCollection:

public static class NVCExtender
{
    public static IDictionary<string, string> ToDictionary(
                                        this NameValueCollection source)
    {
        return source.AllKeys.ToDictionary(k => k, k => source[k]);
    }
}

so you can do the conversion in one line like this:

NameValueCollection Data = new NameValueCollection();
Data.Add("Foo", "baa");

var dict = Data.ToDictionary();

Then you can serialize the dictionary:

var json = new JavaScriptSerializer().Serialize(dict);
// you get {"Foo":"baa"}

But NameValueCollection can have multiple values for one key, for example:

NameValueCollection Data = new NameValueCollection();
Data.Add("Foo", "baa");
Data.Add("Foo", "again?");

If you serialize this you will get {"Foo":"baa,again?"}.

You can modify the converter to produce IDictionary<string, string[]> instead:

public static IDictionary<string, string[]> ToDictionary(
                                    this NameValueCollection source)
{
    return source.AllKeys.ToDictionary(k => k, k => source.GetValues(k));
}

So you can get serialized value like this: {"Foo":["baa","again?"]}.



PS C:\Users\Administrator> # 1. 修复模块路径问题 PS C:\Users\Administrator> $moduleBase = "E:\PowerShellModules\PSHttpClient" PS C:\Users\Administrator> $modulePath = "$moduleBase\1.2.1" PS C:\Users\Administrator> $moduleFile = "$modulePath\PSHttpClient.psm1" PS C:\Users\Administrator> $manifestFile = "$modulePath\PSHttpClient.psd1" PS C:\Users\Administrator> PS C:\Users\Administrator> # 确保目录存在 PS C:\Users\Administrator> New-Item -Path $modulePath -ItemType Directory -Force | Out-Null PS C:\Users\Administrator> PS C:\Users\Administrator> # 2. 创建完全修复的模块文件 PS C:\Users\Administrator> @' >> function Invoke-EnhancedCurlRequest { >> [CmdletBinding()] >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [hashtable]$Headers = @{}, >> [object]$Body, >> [int]$Timeout = 30, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression, >> [switch]$EnableHttp2 >> ) >> >> # 错误类型定义 >> $connectionErrors = @( >> [System.Net.Http.HttpRequestException], >> [System.Net.WebException], >> [System.Net.Sockets.SocketException] >> ) >> >> $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() >> >> try { >> # 关键修复1:使用兼容性更好的TLS设置 >> [System.Net.ServicePointManager]::SecurityProtocol = >> [System.Net.SecurityProtocolType]::Tls12 -bor >> [System.Net.SecurityProtocolType]::Tls13 >> >> # 创建HttpClientHandler >> $handler = New-Object System.Net.Http.HttpClientHandler >> >> # 关键修复2:修复证书验证问题 >> if ($SkipCertificateCheck) { >> $handler.ServerCertificateCustomValidationCallback = { >> param($sender, $cert, $chain, $errors) >> return $true >> } >> } >> >> if ($UseGzipCompression) { >> $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip >> } >> >> # 创建HttpClient >> $client = New-Object System.Net.Http.HttpClient($handler) >> $client.Timeout = [System.TimeSpan]::FromSeconds($Timeout) >> if ($EnableHttp2) { >> $client.DefaultRequestVersion = [System.Net.HttpVersion]::Version20 >> } >> >> # 创建请求消息 >> $request = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::$Method, $Uri) >> >> # 设置User-Agent >> if (-not $Headers.ContainsKey("User-Agent")) { >> $request.Headers.Add("User-Agent", "PowerShell-HTTP-Client/1.0") >> } >> >> # 添加自定义请求头 >> foreach ($key in $Headers.Keys) { >> $request.Headers.TryAddWithoutValidation($key, $Headers[$key]) | Out-Null >> } >> >> # 关键修复3:完全重构表单处理 >> if ($null -ne $Body) { >> $content = $null >> >> # 处理表单数据 - 使用更兼容的方式 >> if ($Body -is [System.Collections.IDictionary]) { >> # 使用NameValueCollection替代泛型集合 >> $formData = New-Object System.Collections.Specialized.NameValueCollection >> foreach ($key in $Body.Keys) { >> $formData.Add($key, $Body[$key].ToString()) >> } >> >> # 创建FormUrlEncodedContent的正确方式 >> $content = New-Object System.Net.Http.FormUrlEncodedContent( >> [System.Collections.Generic.IEnumerable[System.Collections.Generic.KeyValuePair[String,String]]]( >> $formData.AllKeys | ForEach-Object { >> [System.Collections.Generic.KeyValuePair[String,String]]::new( >> $_, >> $formData[$_] >> ) >> } >> ) >> ) >> } >> # 处理JSON数据 >> elseif ($Body -is [string] -and $Body.StartsWith("{") -and $Body.EndsWith("}")) { >> $content = New-Object System.Net.Http.StringContent($Body, [System.Text.Encoding]::UTF8) >> $content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("application/json") >> } >> # 处理文本数据 >> elseif ($Body -is [string]) { >> $content = New-Object System.Net.Http.StringContent($Body, [System.Text.Encoding]::UTF8) >> $content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("text/plain") >> } >> # 处理二进制数据 >> elseif ($Body -is [byte[]]) { >> $content = New-Object System.Net.Http.ByteArrayContent($Body) >> } >> # 其他类型 >> else { >> $content = New-Object System.Net.Http.StringContent($Body.ToString(), [System.Text.Encoding]::UTF8) >> } >> >> $request.Content = $content >> } >> >> # 发送请求 >> $response = $client.SendAsync($request).GetAwaiter().GetResult() >> >> # 处理响应 >> $responseContent = $null >> if ($response.Content -ne $null) { >> $responseContent = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult() >> } >> >> # 返回结果对象 >> [PSCustomObject]@{ >> StatusCode = [int]$response.StatusCode >> StatusMessage = $response.ReasonPhrase >> Content = $responseContent >> Headers = $response.Headers >> Technology = "HttpClient (.NET)" >> Protocol = $response.Version.ToString() >> ElapsedMs = $stopwatch.ElapsedMilliseconds >> } >> } >> catch { >> $statusCode = 500 >> $errorMsg = $_.Exception.Message >> $exceptionType = $_.Exception.GetType().Name >> >> # 识别网络错误 >> foreach ($errType in $connectionErrors) { >> if ($_.Exception -is $errType -or $_.Exception.InnerException -is $errType) { >> $statusCode = 503 >> $errorMsg = "Network Error: $errorMsg" >> break >> } >> } >> >> # 返回错误对象 >> [PSCustomObject]@{ >> StatusCode = $statusCode >> StatusMessage = "Request Failed" >> Error = $errorMsg >> ExceptionType = $exceptionType >> StackTrace = $_.ScriptStackTrace >> } >> } >> finally { >> $stopwatch.Stop() >> if ($client) { $client.Dispose() } >> if ($handler) { $handler.Dispose() } >> } >> } >> >> Export-ModuleMember -Function Invoke-EnhancedCurlRequest >> '@ | Out-File $moduleFile -Encoding UTF8 -Force >> PS C:\Users\Administrator> # 3. 创建模块清单 PS C:\Users\Administrator> @" >> @{ >> RootModule = 'PSHttpClient.psm1' >> ModuleVersion = '1.2.1' >> GUID = '$([guid]::NewGuid().ToString())' >> Author = 'PowerShell User' >> CompanyName = 'N/A' >> Copyright = '(c) $(Get-Date -Format yyyy). All rights reserved.' >> Description = 'Enhanced HTTP client for PowerShell' >> PowerShellVersion = '5.1' >> FunctionsToExport = @('Invoke-EnhancedCurlRequest') >> RequiredAssemblies = @('System.Net.Http') >> } >> "@ | Out-File $manifestFile -Encoding UTF8 -Force >> PS C:\Users\Administrator> # 4. 配置模块路径 PS C:\Users\Administrator> $env:PSModulePath = "$moduleBase;$env:PSModulePath" PS C:\Users\Administrator> [Environment]::SetEnvironmentVariable('PSModulePath', $env:PSModulePath, 'User') PS C:\Users\Administrator> PS C:\Users\Administrator> # 5. 创建全局http函数 PS C:\Users\Administrator> function global:http { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Uri, >> [ValidateSet('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS')] >> [string]$Method = 'GET', >> [object]$Body, >> [hashtable]$Headers, >> [int]$Timeout, >> [switch]$SkipCertificateCheck, >> [switch]$UseGzipCompression, >> [switch]$EnableHttp2 >> ) >> >> $params = @{ >> Uri = $Uri >> Method = $Method >> } >> >> if ($PSBoundParameters.ContainsKey('Body')) { $params['Body'] = $Body } >> if ($PSBoundParameters.ContainsKey('Headers')) { $params['Headers'] = $Headers } >> if ($PSBoundParameters.ContainsKey('Timeout')) { $params['Timeout'] = $Timeout } >> if ($SkipCertificateCheck) { $params['SkipCertificateCheck'] = $true } >> if ($UseGzipCompression) { $params['UseGzipCompression'] = $true } >> if ($EnableHttp2) { $params['EnableHttp2'] = $true } >> >> Invoke-EnhancedCurlRequest @params >> } >> PS C:\Users\Administrator> # 6. 导入模块(使用绝对路径) PS C:\Users\Administrator> Remove-Module PSHttpClient -ErrorAction SilentlyContinue PS C:\Users\Administrator> Import-Module $manifestFile -Force -ErrorAction Stop PS C:\Users\Administrator> PS C:\Users\Administrator> # 7. 运行最终测试 PS C:\Users\Administrator> Write-Host "`n=== 最终测试 ===" -ForegroundColor Cyan === 最终测试 === PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试1:GET请求验证User-Agent PS C:\Users\Administrator> Write-Host "`n[测试1] GET请求 - 验证User-Agent" -ForegroundColor Yellow [测试1] GET请求 - 验证User-Agent PS C:\Users\Administrator> $getResult = http -Method GET -Uri "https://httpbin.org/user-agent" PS C:\Users\Administrator> $getResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs StatusCode : 200 StatusMessage : OK Content : { "user-agent": "PowerShell-HTTP-Client/1.0" } Technology : HttpClient (.NET) Protocol : 1.1 ElapsedMs : 1153 PS C:\Users\Administrator> PS C:\Users\Administrator> # 测试2:POST表单数据 PS C:\Users\Administrator> Write-Host "`n[测试2] POST表单数据" -ForegroundColor Yellow [测试2] POST表单数据 PS C:\Users\Administrator> $formData = @{ >> username = "admin" >> password = "P@ssw0rd!" >> role = "administrator" >> } >> $postResult = http -Method POST -Uri "https://httpbin.org/post" -Body $formData >> $postResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs >> StatusCode : 500 StatusMessage : Request Failed PS C:\Users\Administrator> # 测试3:自签名证书验证 PS C:\Users\Administrator> Write-Host "`n[测试3] 自签名证书验证" -ForegroundColor Yellow [测试3] 自签名证书验证 PS C:\Users\Administrator> $sslResult = http -Method GET -Uri "https://self-signed.badssl.com" -SkipCertificateCheck PS C:\Users\Administrator> $sslResult | Format-List StatusCode, StatusMessage, Content, Technology, Protocol, ElapsedMs StatusCode : 503 StatusMessage : Request Failed PS C:\Users\Administrator> PS C:\Users\Administrator> # 验证结果 PS C:\Users\Administrator> if ($postResult.StatusCode -eq 200 -and $postResult.Content) { >> $json = $postResult.Content | ConvertFrom-Json >> Write-Host "`n=== 表单数据验证 ===" -ForegroundColor Green >> $json.form >> } else { >> Write-Host "`nPOST请求失败!详情:" -ForegroundColor Red >> $postResult | Format-List * >> } >> POST请求失败!详情: StatusCode : 500 StatusMessage : Request Failed Error : 无法将“System.Object[]”类型的“System.Object[]”值转换为“System.Collections.Generic.IEnumerable`1[Sy stem.Collections.Generic.KeyValuePair`2[System.String,System.String]]”类型。 ExceptionType : RuntimeException StackTrace : 在 Invoke-EnhancedCurlRequest、E:\PowerShellModules\PSHttpClient\1.2.1\PSHttpClient.psm1 中: 第 66 行 在 global:http、<无文件> 中: 第 24 行 在 <ScriptBlock>、<无文件> 中: 第 6 行 PS C:\Users\Administrator> if ($sslResult.StatusCode -eq 200) { >> Write-Host "`n自签名证书验证成功!" -ForegroundColor Green >> } else { >> Write-Host "`n自签名证书验证失败!详情:" -ForegroundColor Red >> $sslResult | Format-List * >> } >> 自签名证书验证失败!详情: StatusCode : 503 StatusMessage : Request Failed Error : Network Error: 使用“0”个参数调用“GetResult”时发生异常:“发送请求时出错。” ExceptionType : MethodInvocationException StackTrace : 在 Invoke-EnhancedCurlRequest、E:\PowerShellModules\PSHttpClient\1.2.1\PSHttpClient.psm1 中: 第 98 行 在 global:http、<无文件> 中: 第 24 行 在 <ScriptBlock>、<无文件> 中: 第 1 行 PS C:\Users\Administrator> Write-Host "`n所有修复已完成!系统准备就绪`n" -ForegroundColor Green 所有修复已完成!系统准备就绪
最新发布
08-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值