问题描述
我需要通过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命名空间中的任何内容。
解决方法
答案由@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);
这在我的情况下有效。