找不到类型或命名空间名称“MediaTypeHeaderValue”

1 c# dotnet-httpclient

我使用创建了一个 C# 项目

cd /tmp
dotnet new console -o mydotnetapp
cd mydotnetapp
Run Code Online (Sandbox Code Playgroud)

然后我将 Program.cs 中的代码替换为发送带有自定义 Content-Type 标头的 Web 请求的代码:

cd /tmp
dotnet new console -o mydotnetapp
cd mydotnetapp
Run Code Online (Sandbox Code Playgroud)

我使用它运行它dotnet run并收到此错误:

HttpClient client = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8888/");

request.Headers.Add("Accept", "application/json");

request.Content = new StringContent("18233982904");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?这似乎是我使用旧版本的 HTTP 库时遇到的问题,但我的 .csproj 文件显示我正在使用 .NET 6

/private/tmp/mydotnetapp/Program.cs(8,43): error CS0246: The type or namespace name 'MediaTypeHeaderValue' could not be found (are you missing a using directive or an assembly reference?) [/private/tmp/mydotnetapp/mydotnetapp.csproj]

The build failed. Fix the build errors and run again.
Run Code Online (Sandbox Code Playgroud)

小智 5

它是 System.Net.Http.Headers 命名空间的一部分。

你需要添加这个。

using System.Net.Http.Headers;
Run Code Online (Sandbox Code Playgroud)