如何从另一个调用.NET的Web API的.NET Web API? [关闭]

问题描述 投票:1回答:1

我需要从现有的API调用另一个API。那可能吗?

asp.net api .net-core asp.net-apicontroller
1个回答
3
投票

为了执行Http叫你应该使用位于HttpClient命名空间中的System.Net.Http

欲了解更多信息: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.2

我已经包括了做Post请求的示例:

POST

using System.Net.Http;
using Newtonsoft.Json;

public class MyObject
{
   public string Name{get;set;}
   public int ID{get;set;}
}
public async Task PerformPost(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 PerformPost(myObject);

}
© www.soinside.com 2019 - 2024. All rights reserved.