我正在寻找IHttpClientFactory -> HttpMethod.Post的示例。

huangapple go评论82阅读模式
英文:

I am looking for IHttpClientFactory -> HttpMethod.Post example

问题

我想使用 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);
英文:

I want to use IHttpClientFactory for consuming my API.

There are so many examples on how you can use SendAsync to request data from the API but what if I want to post data using IHttpClientFactory?

I tried something like this but then where do I pass the object?

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

var client = _httpClientFactory.CreateClient();

var response = await client.SendAsync(request);

答案1

得分: 2

这里是一个POST请求的示例,它将一个序列化的对象传递给API,并接收JSON格式的响应以进行反序列化:

var result;

try
{
    HttpClient client = _httpClientFactory.CreateClient("MyAPI");
    //等待响应的超时时间为2分钟
    client.Timeout = new TimeSpan(0, 2, 0);
    //创建一个HttpRequestMessage对象并传递给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();
    //将结果反序列化为适当的对象类型
}
catch (Exception ex)
{
    //记录异常
}
英文:

Here's an example of a POST, it passes a serialized object to the API and receives back JSON for deserialization:

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

得分: 1

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

request.Content = foo; // 这里是传递载荷的地方

`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);
英文:
var request = new HttpRequestMessage(HttpMethod.Post, "https://localhost:44357/api/users/validateuser");

request.Content = foo; //is where you pass the payload

Content is the type of HttpContent which is an abstract class you cannot instantiate it, but you have multiple classes inheriting from it:

ByteArrayContent, MultipartContent, ReadOnlyMemoryContent, StreamContent, FormUrlEncodedContent, MultipartFormDataContent and StringContent. The most common is StringContent so you can serialize your C# object into a JSON string using any kind of JSON serializer (Newtonsoft, System.Text.Json serializer, etc).
Example with Newtonsoft.Json:

using Newtonsoft.Json;


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

huangapple
  • 本文由 发表于 2020年1月6日 22:59:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614323.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定