【问题标题】:Send a string in body via SendRequestAsync通过 SendRequestAsync 在正文中发送字符串
【发布时间】:2021-01-31 18:34:46
【问题描述】:

我需要通过 SendRequestAsync 函数向后端 API 发送补丁请求。这是关于 UWP C# 应用程序。

后端应该是这样的:

在应用程序上,这是我编写的代码。但是不行

if (requestMehtod == ApplicationConstants.RequestType.PATCH)
            {
                Uri uri = new Uri(requestUrl);
                HttpRequestMessage requestMessage = null;
                if (postData != null)
                {
                    var itemAsJson = JsonConvert.SerializeObject(postData);

                    requestMessage = new HttpRequestMessage(HttpMethod.Patch, uri)
                    {
                        Content = new HttpStringContent(itemAsJson, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json-patch+json")
                    };
                }
                else
                {
                    requestMessage = new HttpRequestMessage(HttpMethod.Patch, uri);
                }

                response = await httpClient.SendRequestAsync(requestMessage).AsTask(cancellationTokenSource.Token);
                var rdModel = ProcessResponseData(response);
                return await Handle401Error(rdModel, response, postData, url, requestMehtod, isDownloadSite, OnSendRequestProgress, requestData);
            }

上面的代码可以很好地将 JSON 数据发送到相同的 API 并且工作正常。但我需要知道如何在正文中发送一个字符串。感谢关注

注意:应用使用 Windows.Web.Http 中的 HttpClient,并且无法使用 System.Net.Http 命名空间内的任何内容。

【问题讨论】:

  • 字符串内容不使用序列化的 json 对象,而是使用字符串...
  • 好吧,序列化的 json 对象实际上是一个字符串。您是否尝试过使用 HttpStringContent 类的简单 ctor...Content = new HttpStringContent("myString")
  • 您的问题解决了吗?如果还没有解决,请随时联系我们。
  • @SimonWilson 给了我解决方案。对不起,我忘记更新论坛了。再次感谢您

标签: c# json uwp httpclient win-universal-app


【解决方案1】:

@gusman 和@Simon Wilson 给出了答案。只是为了修改他们的答案,为了能够在请求正文中发送一个字符串,该字符串需要在双引号内。

var requestData = "\"hello world\"";
var request = new HttpRequestMessage(HttpMethod.Post, uri)
                    {
                        Content = new HttpStringContent(requestData, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json")
                    };
                    response = await httpClient.SendRequestAsync(request);

这在我的场景中有效。

【讨论】:

  • 事实上,如果你只是将一个string类型的变量而不是一个复杂类型传递给JsonConvert.Serialze,它会做同样的事情,你手动做的,即用double包裹字符串引号。因为如果您将字符串序列化为 json,就会发生这种情况
猜你喜欢
  • 2013-02-27
  • 2014-08-24
  • 2016-09-02
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多