使用 C#,将 JSON POST 到 REST API 端点;如何从 REST API 接收 JSON 数据。
本文需要 ASP .NET Core,并兼容 .NET Core 3.1、.NET 6和.NET 8。
要从端点获取数据,请参阅本文。
使用 . 将 JSON 数据发布到端点非常容易HttpClient,WebClient并且HttpWebRequest不应使用,因为在撰写本文时它们已被弃用。
将 JSON 发布到端点
private async Task PostJson()
{
string json = System.Text.Json.JsonSerializer.Serialize(new { name = "test" });
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
var response = await client.PostAsync("http://0.0.0.0/endpoint", new StringContent(json, Encoding.UTF8, "application/json"));
var repsonseObject = System.Text.Json.JsonSerializer.Deserialize<object> // NOTE: replace "object" with class name
(await response.Content.ReadAsStringAsync());
// NOTE: use responseObject here
}
}
await PostJson();
使用 JSON Web Token Bearer 身份验证进行 POST
使用 JWT Bearer Authentication 向端点发送 POST 消息非常简单。只需使用HttpRequestMessage类和SendAsync()方法即可。
private async Task PostJsonWithJwtAuth()
{
object? responseObject = null; // NOTE: replace "object" with the class name
string json = System.Text.Json.JsonSerializer.Serialize(new { data = "ABCD1234" });
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
var requestMsg = new HttpRequestMessage(HttpMethod.Post, "http://0.0.0.0/endpoint");
requestMsg.Content = new StringContent(json, Encoding.UTF8, "application/json");
string jwt = "asidlfbvc87w4tguiwebo87w4gqowuy4bfoq4837yo8f3fl"; // NOTE: THIS IS THE JSON WEB TOKEN; REPLACE WITH A REAL JWT
requestMsg.Headers.Add("Authorization", "Bearer " + jwt);
var response = await client.SendAsync(requestMsg);
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
// NOTE: THEN TOKEN HAS EXPIRED; HANDLE THIS SITUATION
}
else if (response.StatusCode == System.Net.HttpStatusCode.NoContent)
responseObject = null;
else if (response.IsSuccessStatusCode)
responseObject = await response.Content.ReadFromJsonAsync<object>(); // NOTE: replace "object" with the class name
}
}
await PostJsonWithJwtAuth();
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。