【问题标题】:I am looking for IHttpClientFactory -> HttpMethod.Post example我正在寻找 IHttpClientFactory -> HttpMethod.Post 示例
【发布时间】:2020-01-06 14:59:51
【问题描述】:

我想使用 IHttpClientFactory 来使用我的 API。

关于如何使用 SendAsync 从 API 请求数据的示例有很多,但如果我想使用 IHttpClientFactory 发布数据怎么办?

我尝试了类似的方法,但是我应该将对象传递到哪里?

var request = new HttpRequestMessage(HttpMethod.Post, "https://localhost:44357/api/users/validateuser");

var client = _httpClientFactory.CreateClient();

var response = await client.SendAsync(request);

【问题讨论】:

    标签: c# .net api httpclient


    【解决方案1】:

    这是一个 POST 的示例,它将一个序列化的对象传递给 API 并接收返回的 JSON 以进行反序列化:

    var result;
    
    try
    {
        HttpClient client = _httpClientFactory.CreateClient("MyAPI");
        //2 minute timeout on wait for response
        client.Timeout = new TimeSpan(0, 2, 0);
        //Create an HttpRequestMessage object and pass it into SendAsync()
        HttpRequestMessage message = new HttpRequestMessage();
        message.Headers.Add("Accept", "application/json");
        message.Content = new StringContent(JsonConvert.SerializeObject(myObj), System.Text.Encoding.UTF8, "application/json");
        message.Method = HttpMethod.Post;
        message.RequestUri = new Uri(client.BaseAddress.ToString() + "someapiendpoint");
    
        HttpResponseMessage response = await client.SendAsync(message);
        result = await response.Content.ReadAsStringAsync();
        //deserialize the result into proper object type
    }
    catch (Exception ex)
    {
        //Log exception
    }
    

    【讨论】:

      【解决方案2】:
      var request = new HttpRequestMessage(HttpMethod.Post, "https://localhost:44357/api/users/validateuser");
      
      request.Content = foo; //is where you pass the payload
      

      Content 是 HttpContent 的类型,这是一个您无法实例化它的抽象类,但您有多个继承自它的类:

      ByteArrayContent、MultipartContent、ReadOnlyMemoryContent、StreamContent、FormUrlEncodedContent、MultipartFormDataContent 和 StringContent。最常见的是StringContent,因此您可以使用任何类型的 JSON 序列化程序(Newtonsoft、System.Text.Json 序列化程序等)将 C# 对象序列化为 JSON 字符串。 以Newtonsoft.Json 为例:

      using Newtonsoft.Json;
      
      
      var jsonContent = JsonConvert.SerializeObject(object);
      request.Content = new StringContent(jsonContent);
      

      【讨论】:

      • 虽然这个纯代码答案实际上可能回答了用户的问题,但最好在其中包含一个解释,以便其他用户能够理解这在原始问题的上下文中意味着什么。跨度>
      • @Christine 感谢您的明智评论!为我的答案添加了更好的描述
      • 你的解释很糟糕。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 2012-02-25
      相关资源
      最近更新 更多