我想使用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);
答案 0 :(得分:2)
这是一个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
}
答案 1 :(得分:0)
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);