【发布时间】:2018-04-30 13:26:18
【问题描述】:
我需要使用第 3 方网络 API。
在这个特定的端点上,我需要使用内容主体 (json) 发出 GET 请求。
var jsonPayload = JsonConvert.SerializeObject(myObject);
var request = new HttpRequestMessage(HttpMethod.Get, endpoint)
{
Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
};
var client = new HttpClient();
var response = await client.SendAsync(request); //<-- explodes with net461,
//but works with netstandard2.0
var responseContent = await response.Content.ReadAsStringAsync();
我将该代码定位到 netstandard2.0 并且它有效。
但是我现在需要在我以net461 为目标的项目中使用它并抛出异常说“Cannot send a content-body with this verb-type”
我知道将内容设置为 GET 请求并不常见,但我无法使用该 api。
- 为什么
HttpClient.Send(request)在我定位net461时失败,但在我定位netstandard2.0时运行良好? - 当我定位
net461时,我有哪些选择?
更新
一种复制方式。
ConsoleApp.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework> <!-- toggle this to net461 -->
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Net.Http" />
</ItemGroup>
</Project>
程序.cs
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var jsonPayload = JsonConvert.SerializeObject(new { });
var request = new HttpRequestMessage(HttpMethod.Get, "http://www.stackoverflow.com")
{
Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json")
};
var client = new HttpClient();
var response = client.SendAsync(request).Result;
var responseContent = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(responseContent);
}
}
}
dotnet --version 显示2.1.104
【问题讨论】:
-
“将内容设置为 GET 请求是不常见的”...如果您要问如何在正确执行的平台上重现错误行为,我想您会不走运。使用 GET 发送请求正文可能不会破坏某些实现,但会通过一些中间硬件传递该请求,并且请求很有可能会崩溃。我会放弃这作为一种策略并坚持标准化行为而不是 RFC/标准破坏行为。实际上,您是在说“我喜欢这个错误……请提供更多错误”。
-
您能否再次运行这两个命令并在任何工具(如 fiddler)中捕获网络跟踪,并查看两个请求负载之间的区别。
-
@xxbbcc 有一些非常流行的产品使用带有正文的 GET 请求来设计他们的 api。一个例子是弹性搜索。以下是此类 api 的示例:elastic.co/guide/en/elasticsearch/reference/current/…
-
@Evk 好的 - 我称之为意外(即使 RFC 允许)。
-
@Evk - 但至少该 API 承认 GET+body 存在问题并允许 POST 作为替代方案。任何只提供 GET+body 的人都处于一个可能存在互操作问题的阴暗世界中。
标签: c# .net httpclient .net-standard