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

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

相关推荐
阿蒙Amon9 天前
《C#图解教程 第5版》深度推荐
开发语言·c#
暖馒9 天前
C#委托与事件的区别
开发语言·c#
JosieBook9 天前
【C#】C#异步编程:异步延时 vs 阻塞延时深度对比
c#·多线程·异步·阻塞
甄天9 天前
WPF中MVVM和MVVMLight模式
c#·wpf·visual studio
冰茶_9 天前
ASP.NET Core API文档与测试实战指南
后端·学习·http·ui·c#·asp.net
_oP_i9 天前
实现 “WebView2 获取word选中内容
开发语言·c#·word
Kookoos9 天前
ABP vNext + Azure Application Insights:APM 监控与性能诊断最佳实践
后端·c#·.net·abp vnext
专注VB编程开发20年9 天前
asp.net core Razor动态语言编程代替asp.net .aspx更高级吗?
开发语言·后端·c#·asp.net·.net
安木夕10 天前
C#.Net筑基-优雅LINQ的查询艺术
c#·.net
软泡芙10 天前
【C#】托管和非托管
java·c#