[英]Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync
I want to send dynamic object like我想发送动态对象,如
new { x = 1, y = 2 };
as body of HTTP POST message.作为 HTTP POST 消息的正文。 So I try to write所以我试着写
var client = new HttpClient();
but I can't find method但我找不到方法
client.PostAsJsonAsync()
So I tried to add Microsoft.AspNetCore.Http.Extensions package to project.json and add所以我尝试将 Microsoft.AspNetCore.Http.Extensions 包添加到 project.json 并添加
using Microsoft.AspNetCore.Http.Extensions;
to uses clause.使用条款。 However It didn't help me.然而它并没有帮助我。
So what is the easiest way to send POST request with JSON body in ASP.NET Core?那么在 ASP.NET Core 中使用 JSON 正文发送 POST 请求的最简单方法是什么?
You should add reference to "Microsoft.AspNet.WebApi.Client" package (read this article for samples). 您应该添加对“ Microsoft.AspNet.WebApi.Client”包的引用(有关示例,请阅读本文 )。
Without any additional extension, you may use standard PostAsync
method: 如果没有任何其他扩展,则可以使用标准的PostAsync
方法:
client.PostAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json"));
where jsonInString
value you can get by calling JsonConvert.SerializeObject(<your object>);
可以通过调用JsonConvert.SerializeObject(<your object>);
获得jsonInString
值JsonConvert.SerializeObject(<your object>);
I use this class: 我使用此类:
public class JsonContent : StringContent
{
public JsonContent(object obj) :
base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
{ }
}
Sample of usage: 用法样本:
new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
I would add to the accepted answer that you would also want to add the Accept
header to the httpClient
: 我要添加到接受的答案中,您也想将Accept
标头添加到httpClient
:
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Microsoft now recommends using an IHttpClientFactory
with the following benefits: Microsoft 现在建议使用具有以下优点的IHttpClientFactory
:
HttpClient
instances.为命名和配置逻辑HttpClient
实例提供一个中心位置。 For example, a client named github could be registered and configured to access GitHub.例如,可以注册并配置名为 github 的客户端访问 GitHub。 A default client can be registered for general access.可以注册默认客户端以进行一般访问。HttpClient
.通过在HttpClient
委派处理程序来编写传出中间件的概念。 Provides extensions for Polly-based middleware to take advantage of delegating handlers in HttpClient
.为基于 Polly 的中间件提供扩展,以利用HttpClient
的委托处理程序。HttpClientMessageHandler
instances.管理底层HttpClientMessageHandler
实例的池和生命周期。 Automatic management avoids common DNS (Domain Name System) problems that occur when manually managing HttpClient
lifetimes.自动管理避免了手动管理HttpClient
生命周期时出现的常见 DNS(域名系统)问题。ILogger
) for all requests sent through clients created by the factory.为通过工厂创建的客户端发送的所有请求添加可配置的日志记录体验(通过ILogger
)。https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1
Setup:设置:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
// Remaining code deleted for brevity.
POST example: POST 示例:
public class BasicUsageModel : PageModel
{
private readonly IHttpClientFactory _clientFactory;
public BasicUsageModel(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task CreateItemAsync(TodoItem todoItem)
{
var todoItemJson = new StringContent(
JsonSerializer.Serialize(todoItem, _jsonSerializerOptions),
Encoding.UTF8,
"application/json");
var httpClient = _clientFactory.CreateClient();
using var httpResponse =
await httpClient.PostAsync("/api/TodoItems", todoItemJson);
httpResponse.EnsureSuccessStatusCode();
}
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#make-post-put-and-delete-requests https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#make-post-put-and-delete-requests
You can use IEnterprise.Easy-HTTP since it has built in class parsing: 您可以使用IEnterprise.Easy-HTTP,因为它已内置了类解析功能:
await new RequestBuilder<ExampleObject>()
.SetHost("https://httpbin.org")
.SetContentType(ContentType.Application_Json)
.SetType(RequestType.Post)
.SetModelToSerialize(dto)
.Build()
.Execute();
You are right that this has long since been implemented in .NET Core. 没错,这早已在.NET Core中实现。
At the time of writing (September 2019), the project.json
file of NuGet 3.x+ has been superseded by PackageReference
(as explained at https://docs.microsoft.com/en-us/nuget/archive/project-json ). 在撰写本文时(2019年9月),NuGet 3.x +的project.json
文件已由PackageReference
取代(如https://docs.microsoft.com/en-us/nuget/archive/project-json中所述) )。
To get access to the *Async
methods of the HttpClient
class, your .csproj
file must be correctly configured. 要访问HttpClient
类的*Async
方法,必须正确配置.csproj
文件。
Open your .csproj
file in a plain text editor, and make sure the first line is 在纯文本编辑器中打开您的.csproj
文件,并确保第一行是
<Project Sdk="Microsoft.NET.Sdk.Web">
(as pointed out at https://docs.microsoft.com/en-us/dotnet/core/tools/project-json-to-csproj#the-csproj-format ). (如https://docs.microsoft.com/en-us/dotnet/core/tools/project-json-to-csproj#the-csproj-format所指出)。
To get access to the *Async
methods of the HttpClient
class, you also need to have the correct package reference in your .csproj
file, like so: 要访问HttpClient
类的*Async
方法,还需要在.csproj
文件中具有正确的包引用 ,如下所示:
<ItemGroup>
<!-- ... -->
<PackageReference Include="Microsoft.AspNetCore.App" />
<!-- ... -->
</ItemGroup>
(See https://docs.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#adding-a-packagereference . Also: We recommend applications targeting ASP.NET Core 2.1 and later use the Microsoft.AspNetCore.App metapackage , https://docs.microsoft.com/en-us/aspnet/core/fundamentals/metapackage ) (请参阅https://docs.microsoft.com/zh-cn/nuget/consume-packages/package-references-in-project-files#adding-a-packagereference 。此外: 我们建议针对ASP.NET Core 2.1和以后使用Microsoft.AspNetCore.App元包 , https: //docs.microsoft.com/zh-cn/aspnet/core/fundamentals/metapackage )
Methods such as PostAsJsonAsync
, ReadAsAsync
, PutAsJsonAsync
and DeleteAsync
should now work out of the box. PostAsJsonAsync
, ReadAsAsync
, PutAsJsonAsync
和DeleteAsync
现在应该可以立即使用。 (No using directive needed.) (无需使用指令。)
Update: The PackageReference tag is no longer needed in .NET Core 3.0. 更新: .NET Core 3.0中不再需要PackageReference标记。
You can (and should) use the PostAsJsonAsync
extension method from System.Net.Http.Json :您可以(并且应该)使用System.Net.Http.Json 中的PostAsJsonAsync
扩展方法:
httpClient.PostAsJsonAsync(url, {
x = 1,
y = 2
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.