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

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

相关推荐
lljss20206 小时前
C# 一个解决方案放一个dll项目,一个dll测试项目 ,调试dll项目的源码
c#
ghost14314 小时前
C#学习第27天:时间和日期的处理
开发语言·学习·c#
jason成都14 小时前
c#压缩与解压缩-SharpCompress
开发语言·c#
傻啦嘿哟15 小时前
从零开始:用Tkinter打造你的第一个Python桌面应用
开发语言·c#
CodeCraft Studio16 小时前
PDF处理控件Aspose.PDF教程:在 C# 中更改 PDF 页面大小
前端·pdf·c#
InCerry17 小时前
.NET周刊【5月第4期 2025-05-25】
c#·.net·.net周刊
阿蒙Amon20 小时前
C#获取磁盘容量:代码实现与应用场景解析
开发语言·c#
界面开发小八哥20 小时前
VS代码生成工具ReSharper v2025.1——支持.NET 10和C# 14预览功能
开发语言·ide·c#·.net·visual studio·resharper
CN.LG21 小时前
C# 从 ConcurrentDictionary 中取出并移除第一个元素
java·开发语言·c#
vvilkim1 天前
ASP.NET Core 中间件深度解析:构建灵活高效的请求处理管道
后端·中间件·asp.net