首页 > 解决方案 > 发送带有请求正文的http get c#

问题描述

我想发送一个带有请求正文的 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);

标签: c#getdotnet-httpclient

解决方案


推荐阅读