c# - 如何从另一个 .net API 调用 .net API?

标签 c# asp.net api .net-core

是否可以从 .net 中的现有 API 调用 API?如果是,我们如何调用?

最佳答案

要执行 Http 调用,您应该使用位于 System.Net.Http 命名空间中的 HttpClient

了解更多信息:
https://learn.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);

}

关于c# - 如何从另一个 .net API 调用 .net API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54568389/

相关文章:

c# - 停止命令提示符关闭得如此之快

c# - .net4 上的 SHA1 生成

c# - WPF 自定义布局/虚拟化

c# - 连接到 SQL Server 并插入值

asp.net - 作为使用 Visual Studio 的 ASP.NET Web 开发人员,我应该安装 IIS 吗?

android - 保护来自 Android 应用程序的 API 调用

java - 在 Blackberry 上调整位图大小,同时保留 Alpha 数据

c# - 检测到文本框有一个数字和一个大写字母

c# - 使用控制台应用程序创建 ASP.NET Web API

api - 类/接口(interface) "Default"实现的命名约定