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>);
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)
Ser*_*gan 11
我会添加到您接受的答案,您还要将Accept标题添加到httpClient:
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Run Code Online (Sandbox Code Playgroud)
如果您使用 .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)
Microsoft now recommends using an IHttpClientFactory with the following benefits:
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.HttpClient. Provides extensions for Polly-based middleware to take
advantage of delegating handlers in HttpClient.HttpClientMessageHandler instances. Automatic management avoids
common DNS (Domain Name System) problems that occur when manually
managing HttpClient lifetimes.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)
| 归档时间: |
|
| 查看次数: |
123002 次 |
| 最近记录: |