我的HTTPClient发布消息的正文不适用于我的服务器

时间:2019-03-25 13:42:20

标签: c# post asp.net-web-api httpclient

由于以下代码(在Xamarin中),我尝试发送REST Post请求:

            HttpResponseMessage response = null;
        using (var client = new HttpClient())
        {
            using (var request = new HttpRequestMessage(HttpMethod.Post, requestURI))
            {
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", app.OAuth_Token);
                string content = JsonConvert.SerializeObject(OrderedItem);
                if (content != null)
                {
                    request.Content = new StringContent(content, Encoding.UTF8, "application/json");
                }

                response = await client.SendAsync(request).ConfigureAwait(false);
                var responseString = await response.Content.ReadAsStringAsync();
            }
        }

服务器很好地捕获了该消息。但是身体是空的... 这是字符串内容->

"{\"ItemId\":5,\"Quantity\":1,\"SelectedSize\":null,\"SelectedSalt\":false,\"SelectedHotNotCold\":false,\"SelectedMeatId\":null,\"SelectedSauceId\":null}"

服务器正在以下列方式在ASP.Net Web.api上工作:

            public async Task<IHttpActionResult> Post([FromBody]string value)
    {
        if (value == null)
            return BadRequest("Body cannot be null");

... some code 
}

奇怪的是,我与Postman一起测试了请求,并且一切正常...

编辑

通过以下方式更改标题,我可以获得消息内容:

        public async Task<IHttpActionResult> Post(object value)
    {
        if (value == null)
            return BadRequest("Body cannot be null");
    ... other code 
    }

对象的内容如下:

{{  "ItemId": 4,  "Quantity": 1,  "SelectedSize": null,  "SelectedSalt": alse,  "SelectedHotNotCold": false,  "SelectedMeatId": null,  "SelectedSauceId": null}}

因此,我感到HttpRequest中的内容已在路径上的某处进行了修改...出现了两个新的外括号...

0 个答案:

没有答案