c# - 如何从另一个 .net API 调用 .net API?
问题描述
是否可以从 .net 中的现有 API 调用 API?如果是,我们如何调用?
解决方案
为了执行Http
调用,您应该使用HttpClient
位于System.Net.Http
命名空间中的 。
欲了解更多信息:https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.2
我已经包含了一个执行Post
请求的示例:
邮政
using System.Net.Http;
using Newtonsoft.Json;
public class MyObject
{
public string Name{get;set;}
public int ID{get;set;}
}
public async Task PerformPostAsync(MyObject obj)
{
try
{
HttpClient client=new HttpClient();
string str = JsonConvert.SerializeObject(obj);
HttpContent content = new StringContent(str, Encoding.UTF8, "application/json");
var response = await this.client.PostAsync("http://[myhost]:[myport]/[mypath]",
content);
string resp = await response.Content.ReadAsStringAsync();
//deserialize your response using JsonConvert.DeserializeObject<T>(resp)
}
catch (Exception ex)
{
//treat your exception here ...
//Console.WriteLine("Threw in client" + ex.Message);
//throw;
}
}
public static async Task Main(){
MyObject myObject=new MyObject{ID=1,Name="name"};
await PerformPostAsync(myObject);
}
推荐阅读
- flutter - 运行 Flutter 应用程序时 PC 出现延迟
- android - 获取手机的 z 轴和磁北极之间的角度(而不是 y 轴)
- php - 如何拆分字符串并向其添加额外的字符串
- swiftui - 使用 SwiftUI 中的列表和可识别协议使 ScrollViewReader 滚动到项目
- javascript - 在连接两个数组时,在连接数组的后面加上(数字)递增的非唯一值
- javascript - 在角度模板性能中连接字符串
- java - 获取 java.lang.SecurityException - “org.hamcrest.Matchers”的签名者信息不匹配
- python - 尝试从从其他文件导入的函数中读取数据时出现问题
- c++ - 错误构建 Qt6 在哪里可以找到错误日志?
- javascript - 如何连接字符串并向其添加 html 标签?