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

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

相关推荐
网际游侠2 小时前
一份C#的笔试题及答案
面试·c#·笔试
木木黄木木3 小时前
使用 Theos 开发 iOS 应用(IPA)记事本
ios·c#
Tatalaluola3 小时前
【Quest开发】手柄交互震动
unity·c#·游戏引擎·vr·quest
“抚琴”的人4 小时前
C#—线程池详解
开发语言·c#
kkk16222456 小时前
C# Winform 实现换肤,并自定义皮肤功能
java·算法·c#
妮妮学代码6 小时前
c#:使用串口通讯实现数据的发送和接收
开发语言·c#
初级代码游戏9 小时前
VSTO(C#)Excel开发9:处理格式和字体
c#·excel·vba·vsto
大巨头9 小时前
C#EF 拉姆表达式和linq 使用方法和区别
后端·c#
大巨头10 小时前
C# linq 查询语法与方法语法示例
后端·c#
穷的捡破烂儿10 小时前
C#开发笔记:INI文件操作
笔记·c#