ASP.NET Core 如何使用 C# 从端点发出 GET 请求

使用 C#,从 REST API 端点获取 JSON;如何从 REST API 接收 JSON 数据。

本文需要 ASP .NET Core,并兼容 .NET Core 3.1、.NET 6和.NET 8。

要将数据发布到端点,请参阅本文。

使用 . 从端点发布 GET 数据非常容易HttpClient,WebClient并且HttpWebRequest不应使用,因为在撰写本文时它们已被弃用。

从端点获取 JSON

private async Task GetJson()

{

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.GetAsync("http://0.0.0.0/endpoint");

var repsonseObject = System.Text.Json.JsonSerializer.Deserialize<object> // NOTE: replace "object" with class name

(await response.Content.ReadAsStringAsync());

// NOTE: use responseObject here

}

}

await GetJson();

使用 JSON Web Token Bearer 身份验证获取

使用 JWT Bearer Authentication 从端点获取数据非常简单。只需使用HttpRequestMessage类和SendAsync()方法即可。

private async Task GetJsonWithJwtAuth()

{

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.Get, "http://0.0.0.0/endpoint");

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 GetJsonWithJwtAuth();

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
吃一碗粉只付一碗钱23 分钟前
16-SqlSugar多库ConfigId与按实体选连接
sqlserver·c#
rockey6272 小时前
AScript之字符串模板
c#·.net·script·expression·动态脚本
will_net3 小时前
Redis集群部署+Redis 链接地址放入Aollo +c#项目接入Redis
redis·c#·bootstrap
BuHuaX10 小时前
Lua 与 ToLua:运行机制及热更新原理
开发语言·unity·junit·c#·lua
asdzx6710 小时前
C# 操作 PDF 元数据:从属性写入到字段提取的完整流程
前端·pdf·c#
氷凌公子12 小时前
算法与UI拆分中遇到的问题及解决方式
c#·onnx·yolov26
1-1=012 小时前
C# 泛型
c#·.net·.netcore
椒颜皮皮虾྅1 天前
让文档不止于文字:DeploySharp + PP-Structure,打通版面分析与表格重建
开发语言·学习·c#·.net·cuda
椒颜皮皮虾྅2 天前
一套 C# 接口,解锁四类视觉任务:DeploySharp 分类、分割、关键点与旋转框实战
开发语言·分类·c#