[英]Send Post and Get result in same call using HttpClient
If Method A posts as follows: 如果方法A发布如下:
public void testPostAndGet()
{
using (var client = new HttpClient())
{
var uri = new Uri("https://localhost:44322/test");
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("email", "email@test.com")
};
var content = new FormUrlEncodedContent(pairs);
var responsePost = client.PostAsync(uri, content).Result;
if (responsePost.IsSuccessStatusCode)
{
}
}
}
To method B, which also returns a List
: 返回方法B,该方法还返回一个
List
:
public async Task<List<EventItem>> test()
{
List<EventItem> items = new List<EventItem>();
NameValueCollection nvc = Request.Form;
string email = nvc["email"];
string test = "";
try
{
items = await eventsService.GetAllEvents(graphClient, email);
}
catch (ServiceException se)
{
}
return items;
}
How can I access the List
returned from method B from method A? 如何从方法A访问方法B返回的
List
? ie How can I send a Post and Get in the same call to the same endpoint? 即我如何发送帖子并在同一呼叫中到达同一端点?
something like this will work: 这样的事情将工作:
public async Task<TResult> PostAsync<TResult, TInput>(string uriString, TInput payload = null) where TInput : class
{
var uri = new Uri(uriString);
using (var client = GetHttpClient())
{
var jsonContent = JsonConvert.SerializeObject(payload, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
HttpResponseMessage response = await client.PostAsync(uri, new StringContent(jsonContent, Encoding.UTF8, "application/json"));
if (response.StatusCode != HttpStatusCode.OK)
{
//Log.Error(response.ReasonPhrase);
return default(TResult);
}
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResult>(json);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.