使用HttpClient PostAsJsonAsync在ASP.NET Core中发送HTTP POST消息

Rem*_*Rem 110 c# .net-core asp.net-core

我想发送动态对象

new { x = 1, y = 2 };
Run Code Online (Sandbox Code Playgroud)

作为HTTP POST消息的主体.所以我试着写

var client = new HttpClient();
Run Code Online (Sandbox Code Playgroud)

但我找不到方法

client.PostAsJsonAsync()
Run Code Online (Sandbox Code Playgroud)

所以我尝试将Microsoft.AspNetCore.Http.Extensions包添加到project.json并添加

using Microsoft.AspNetCore.Http.Extensions; 
Run Code Online (Sandbox Code Playgroud)

使用条款.但它没有帮助我.

那么在ASP.NET Core中使用JSON主体发送POST请求的最简单方法是什么?

Set*_*Set 162

您应该添加对"Microsoft.AspNet.WebApi.Client"包的引用(阅读本文的示例).

没有任何额外的扩展,您可以使用标准PostAsync方法:

client.PostAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json"));
Run Code Online (Sandbox Code Playgroud)

其中jsonInString值可以通过调用得到JsonConvert.SerializeObject(<your object>);

  • 当然。但我问这个问题是为了找出我是否遗漏了什么。我不敢相信它还没有在 Core 中实现! (2认同)

sto*_*ran 84

我用这个班:

public class JsonContent : StringContent
{
    public JsonContent(object obj) :
        base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
    { }
}
Run Code Online (Sandbox Code Playgroud)

使用样本:

new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
Run Code Online (Sandbox Code Playgroud)

  • 为什么不是扩展方法?public static class JsonContent {public Task <?> PostAsJSonAsync(此HttpClient客户端,对象toSerializeAsJson){...}} (5认同)
  • 我喜欢 JsonContent 类方法 (2认同)

Ser*_*gan 11

我会添加到您接受的答案,您还要将Accept标题添加到httpClient:

httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Run Code Online (Sandbox Code Playgroud)


Mar*_*ijk 8

如果您使用 .NET 5 或更高版本,您可以(并且应该)使用System.Net.Http.JsonPostAsJsonAsync中的扩展方法:

httpClient.PostAsJsonAsync(url, new { 
    x = 1, 
    y = 2 
});
Run Code Online (Sandbox Code Playgroud)

如果您使用的是旧版本的.NET Core,您可以自己实现扩展功能:

public static class HttpClientExtensions
{
    public static Task<HttpResponseMessage> PostJsonAsync(this HttpClient httpClient, string url, object body)
    {
        var bodyJson = JsonSerializer.Serialize(body);
        var stringContent = new StringContent(bodyJson, Encoding.UTF8, "application/json");
        return httpClient.PostAsync(url, stringContent);
    }
}
Run Code Online (Sandbox Code Playgroud)


Ogg*_*las 5

Microsoft now recommends using an IHttpClientFactory with the following benefits:

  • Provides a central location for naming and configuring logical HttpClient instances. For example, a client named github could be registered and configured to access GitHub. A default client can be registered for general access.
  • Codifies the concept of outgoing middleware via delegating handlers in HttpClient. Provides extensions for Polly-based middleware to take advantage of delegating handlers in HttpClient.
  • Manages the pooling and lifetime of underlying HttpClientMessageHandler instances. Automatic management avoids common DNS (Domain Name System) problems that occur when manually managing HttpClient lifetimes.
  • Adds a configurable logging experience (via ILogger) for all requests sent through clients created by the factory.

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.
Run Code Online (Sandbox Code Playgroud)

POST example:

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();
    }
Run Code Online (Sandbox Code Playgroud)

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#make-post-put-and-delete-requests