response.ContentType ="text/plain";

本文介绍ASP.NET中如何设置响应的内容类型为纯文本,并探讨在使用Response.Write()前后调用Response.End()的影响。

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

 response.ContentType ="text/plain";在Response.Write("");之前,之后可以用Response.End();

那你看看最新的CurlTools.psm1,还有没有哪里需要优化或者修改:“function Invoke-CurlRequest { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$Url, [string]$Method = "GET", [hashtable]$Headers = @{}, [string]$Body, [string]$ContentType = "application/json", [ValidateSet("Raw", "Object")] [string]$OutputType = "Raw", [switch]$IncludeHeaders, [switch]$FollowRedirect, [int]$MaxRedirects = 10, [int]$Timeout = 0, [string]$OutputFile, [switch]$Insecure ) # 保存原始语言环境 $originalLang = $env:LANG $originalLC_ALL = $env:LC_ALL # 初始化响应对象 $response = [PSCustomObject]@{ Status = $null Content = $null Data = $null ErrorMessage = $null ErrorType = $null Url = $Url Method = $Method StatusCode = $null Headers = $null Latency = $null Size = $null Timestamp = (Get-Date) RawOutput = $null } # 计时器开始 $stopwatch = [System.Diagnostics.Stopwatch]::StartNew() try { # 设置英文环境防止乱码 $env:LANG = 'C' $env:LC_ALL = 'C' # 构建 curl 命令参数 $curlArgs = @( $Url, "-X", $Method, "--silent", "--show-error" ) # 添加可选参数 if ($IncludeHeaders) { $curlArgs += "-i" } if ($FollowRedirect) { $curlArgs += "-L" $curlArgs += "--max-redirs" $curlArgs += $MaxRedirects } if ($Timeout -gt 0) { $curlArgs += "--connect-timeout" $curlArgs += [math]::Ceiling($Timeout/2) $curlArgs += "--max-time" $curlArgs += $Timeout } if ($OutputFile) { $curlArgs += "-o" $curlArgs += $OutputFile } if ($Insecure) { $curlArgs += "--insecure" } # 添加默认User-Agent if (-not $Headers.ContainsKey('User-Agent')) { $Headers['User-Agent'] = "PowerShell CurlTools/1.0" } # 添加内容类型头 if (-not $Headers.ContainsKey("Content-Type") -and $Body) { $Headers["Content-Type"] = $ContentType } # 添加请求头 foreach ($key in $Headers.Keys) { $curlArgs += "-H" $curlArgs += "$key`: $($Headers[$key])" } # 添加请求体 if ($Body) { $curlArgs += "-d" $curlArgs += $Body } # 修复中文乱码:使用英文日志 Write-Verbose "Executing curl command: curl $($curlArgs -join ' ')" # 执行 curl 命令 $rawOutput = if ($OutputFile) { # 直接输出到文件 curl.exe @curlArgs 2>&1 } else { # 捕获输出 $output = curl.exe @curlArgs 2>&1 if ($null -ne $output) { # 修复中文乱码:转换为UTF8 $utf8Output = $output | Out-String | ForEach-Object { [System.Text.Encoding]::UTF8.GetString( [System.Text.Encoding]::GetEncoding(0).GetBytes($_) ) } $utf8Output } } $curlExitCode = $LASTEXITCODE # 保存原始输出用于调试 $response.RawOutput = $rawOutput # 计算请求耗时 $response.Latency = $stopwatch.ElapsedMilliseconds # 处理 curl 错误 if ($curlExitCode -ne 0) { $response.Status = "Error" $response.ErrorMessage = ExtractCurlError $rawOutput $response.Content = $rawOutput $response.ErrorType = switch ($curlExitCode) { 6 { "DNSResolutionFailed" } 7 { "ConnectionFailed" } 28 { "Timeout" } default { "CurlError" } } $response.StatusCode = 0 # 明确设置为0表示网络错误 return $response } # 如果是文件输出模式 if ($OutputFile) { if (Test-Path $OutputFile) { $response.Status = "Success" # 修复中文乱码:使用英文消息 $response.Content = "Content saved to file: $OutputFile" $response.Size = (Get-Item $OutputFile).Length $response.StatusCode = 200 } else { $response.Status = "Error" $response.ErrorMessage = "File output failed: $OutputFile" $response.StatusCode = 0 } return $response } # 记录响应大小 $response.Size = $rawOutput.Length # 分离响应头和内容 $headerSection = $null $responseBody = $rawOutput $statusCode = 0 # 增强头部分离逻辑 if ($IncludeHeaders -or $rawOutput -match '^HTTP/') { # 尝试不同换行符查找头部结束位置 $lineEndings = @("`r`n`r`n", "`n`n", "`r`r") $headerEnd = $null foreach ($ending in $lineEndings) { $pos = $rawOutput.IndexOf($ending) if ($pos -gt -1) { $headerEnd = $pos break } } # 分离头部和主体 if ($null -ne $headerEnd -and $headerEnd -gt 0) { $headerSection = $rawOutput.Substring(0, $headerEnd) $responseBody = $rawOutput.Substring($headerEnd + $ending.Length) # 解析状态码 if ($headerSection -match 'HTTP/\d+\.\d+\s+(\d{3})') { $statusCode = [int]$matches[1] } # 解析响应头 $response.Headers = @{} $headerLines = $headerSection -split "`r`n|`n" foreach ($line in $headerLines) { if ($line -match '^([^:]+):\s*(.+)') { $response.Headers[$matches[1]] = $matches[2].Trim() } } } } # 设置状态码 $response.StatusCode = $statusCode # 设置响应状态 if ($statusCode -ge 400) { $response.Status = "Error" } elseif ($statusCode -eq 204) { $response.Status = "NoContent" } else { $response.Status = "Success" } # 处理空响应 if ([string]::IsNullOrWhiteSpace($responseBody) -and $statusCode -eq 204) { $response.Content = "" return $response } # 原始输出模式 if ($OutputType -eq "Raw") { $response.Content = $rawOutput return $response } # 对象模式 - 尝试解析JSON $response.Content = $responseBody try { $parsedData = $responseBody | ConvertFrom-Json -ErrorAction Stop # 智能提取嵌套数据 if ($parsedData.PSObject.Properties.Name -contains "json") { $response.Data = $parsedData.json } elseif ($parsedData.PSObject.Properties.Name -contains "data") { try { $response.Data = $parsedData.data | ConvertFrom-Json } catch { $response.Data = $parsedData.data } } else { $response.Data = $parsedData } # 如果是错误响应,提取错误信息 if ($response.Status -eq "Error") { $response.ErrorMessage = ExtractApiError $response.Data } return $response } catch { # 非JSON响应 if ($response.Status -eq "Success") { $response.Status = "NonJsonResponse" } # 智能检测内容类型 if ($responseBody -match '<!DOCTYPE html>') { $response.Headers['Content-Type'] = 'text/html' } elseif ($responseBody -match '^{') { $response.Headers['Content-Type'] = 'application/json' } elseif (-not $response.Headers['Content-Type']) { $response.Headers['Content-Type'] = 'text/plain' } # 如果是错误响应,设置错误信息 if ($response.Status -eq "Error") { $response.ErrorMessage = "Non-JSON error response" } return $response } } catch { $response.Status = "Error" $response.ErrorMessage = $_.Exception.Message $response.Content = $_.Exception.Message return $response } finally { # 恢复原始语言环境 $env:LANG = $originalLang $env:LC_ALL = $originalLC_ALL $stopwatch.Stop() } } # 辅助函数:提取curl错误信息 function ExtractCurlError([string]$content) { if ($content -match 'curl: \(\d+\) (.*)') { return $matches[1] } return $content } # 辅助函数:提取API错误信息 function ExtractApiError($responseData) { # 尝试从常见结构中提取错误信息 $errorKeys = @("error", "message", "detail", "description", "error_message") foreach ($key in $errorKeys) { if ($null -ne $responseData -and $responseData.PSObject.Properties.Name -contains $key) { $errorValue = $responseData.$key if ($errorValue -is [string]) { return $errorValue } elseif ($errorValue -is [psobject]) { return ($errorValue | Format-List | Out-String).Trim() } } } # 没有找到特定错误字段,返回整个响应 if ($null -ne $responseData) { return ($responseData | Format-List | Out-String).Trim() } return "Unknown API error" } # 导出模块函数 Export-ModuleMember -Function Invoke-CurlRequest, ExtractCurlError, ExtractApiError”
最新发布
08-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值