使用HttpClient发送发布并获得相同调用的结果

时间:2017-02-09 10:00:39

标签: c# .net dotnet-httpclient

如果方法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)
                {

                }
            }
        }

方法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;
        }

如何从方法A访问方法B返回的List? 即如何发送帖子并将同一个呼叫发送到同一个端点?

1 个答案:

答案 0 :(得分:0)

这样的事情会起作用:

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);
        }
    }