发送带有请求正文的http get C#

时间:2018-11-29 23:38:27

标签: c# get dotnet-httpclient

我想发送带有请求正文的HTTP GET。我知道关于是否应该执行此操作有很多激烈的辩论,但是我对辩论并不感兴趣,我只是想这样做。我正在使用C#和ASP.NET,下面是我的代码。不幸的是,它引发了一个异常“无法使用此动词类型发送内容主体”。拜托,我们将非常感谢您提供有关如何完成此操作的帮助!

// Serialize our concrete class into a JSON String
            var stringPayload = JsonConvert.SerializeObject(memRequest);

            // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
            var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

            using (var httpClient = new HttpClient())
            {
                HttpRequestMessage request = new HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = u,
                    Content = httpContent
                };

                var result = httpClient.SendAsync(request).Result;
                result.EnsureSuccessStatusCode();

                var responseBody = result.Content.ReadAsStringAsync().ConfigureAwait(false);

0 个答案:

没有答案