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

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

相关推荐
暖馒5 小时前
Modbus应用层协议的深度剖析
网络·网络协议·c#·wpf·智能硬件
刘欣的博客8 小时前
C# CS架构程序发版升级的走数据库方案
c#·单文件升级自己的方式
Yorlen_Zhang9 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
不绝19110 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
大鹏说大话10 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#
czhc114007566311 小时前
通信 28
c#
bugcome_com15 小时前
C# 程序结构详解:从 Hello World 开始
c#
唐梓航-求职中15 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
bugcome_com18 小时前
阿里云 OSS C# SDK 使用实践与参数详解
阿里云·c#
大尚来也18 小时前
双库协同,各取所长:.NET Core 中 PostgreSQL 与 SQLite 的优雅融合实战
postgresql·sqlite·.netcore