Swagger请求正常但PowerShell curl发送Post返回400错误如何解决
问题解决方法
返回400错误是因为请求格式不符合接口要求,主要有两个核心问题需要修正:
1. 修正请求头的写法
PowerShell哈希表的键值对格式有误,原命令里"Content-Type" ="application/json"的多余引号和空格会导致解析错误,正确的请求头写法应该是:
@{ accept = '*/*'; Content-Type = 'application/json' }
2. 确保请求体是合法JSON格式
因为你指定了Content-Type = application/json,接口会要求请求体必须是合法的JSON字符串。你传入的"test"不是有效的JSON,需要调整格式:
- 如果接口接受简单字符串参数,Body写为
'"test"'(外层用单引号包裹,内层用双引号把内容封装成JSON字符串) - 如果接口需要特定的JSON对象结构(参考Swagger里的请求体示例),比如要求传
{"content":"test"},则Body写为'{"content":"test"}'
修正后的完整命令
以简单字符串JSON为例:
curl -Method Post -Uri "http://localhost:32774/WeatherForecast" -Headers @{ accept = '*/*'; Content-Type = 'application/json' } -Body '"test"'
或者直接使用Invoke-WebRequest(PowerShell里的curl是它的别名,用原名更清晰,避免和系统原生curl混淆):
Invoke-WebRequest -Method Post -Uri "http://localhost:32774/WeatherForecast" -Headers @{ accept = '*/*'; Content-Type = 'application/json' } -Body '"test"'
进一步排查问题
如果还是报错,可以查看响应的详细错误信息,明确具体问题点:
$resp = Invoke-WebRequest -Method Post -Uri "http://localhost:32774/WeatherForecast" -Headers @{ accept = '*/*'; Content-Type = 'application/json' } -Body '"test"' -ErrorAction SilentlyContinue # 查看状态码和响应内容 $resp.StatusCode $resp.Content
内容的提问来源于stack exchange,提问作者user2463506
相关产品推荐
相关产品推荐

