如何在.NET中格式化POST请求

时间:2018-11-20 18:14:54

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

我有一个POST参数,例如:

var requestJson = $@"{{""positionsQuery"":{{""positionDate"":[""{positionDate.Date:yyyyMMdd}""]}},""measures"":[""margin""]}}";

这产生\,因此Fiddler将其显示为

"{\"positionsQuery\":{\"positionDate\":[\"20181119\"]},\"measures\":[\"margin\"]}"

结果是请求失败。我需要做的是工作

{"positionsQuery":{"positionDate":["20181119"]},"measures":["margin"]}

在此之前,我尝试过“ Json.Net”

        var request = new { PositionsQuery = new { PositionDate = new [] { positionDate.Date.ToString("yyyyMMdd") } }, Measures = new [] { "margin" }};
        var requestJson = JsonConvert.SerializeObject(request, new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        });
        var response = (await _httpClient.PostAsync(url, requestJson).ConfigureAwait(false));

仍然有\引起问题(Fiddler屏幕截图)。

Fiddler screenshot

谢谢! 如何格式化请求?

1 个答案:

答案 0 :(得分:1)

不要手动构建JSON字符串。构建对象并序列化它要干净得多。

var requestJson = Newtonsoft.Json.JsonConvert.SerializeObject(
    new
    {
        positionsQuery = new
        {
            positionDate = positionDate.Date.ToString("yyyyMMdd")
        },
        measures = new []{"margin"}
    });