PostAsJsonAsync 向请求正文添加前导字符

PostAsJsonAsync adding leading character to request body

我在尝试使用 PostAsJsonAsync 时遇到奇怪的问题。 在正文中,我得到这个 json 带有奇怪的前导和尾随字符:

99 {

"SessionReferenceId":"f39dc178-279e-4e3a-bda9-a16829eb0e45",

"GameReferenceId":"netent_es_starburst",

"CurrencyCode":"EUR",

"LossLimit":100,

"ClientType":1

}

0

并且在 API 方面无法绑定,我收到错误消息,指出请求不能有空主体。

发送端的代码是这样的:

using(var client = new SGSClient()) {
  var model = new CashSessionCreateModel()
            {
             ClientType = ClientType.DesktopBrowser,
             CurrencyCode = "EUR",
             GameReferenceId = "netent_es_starburst",
             LossLimit = 100,
             SessionReferenceId = "f39dc178-279e-4e3a-bda9-a16829eb0e45"
           };

 HttpResponseMessage response = client.PostAsJsonAsync(apiUrl, model).Result;
}

添加 HTTPClient 配置:

public SGSHttpClient()
        {
            var appSettingsFilePath = $"Configuration\appSettings.json";

            // Build Configuration
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile(appSettingsFilePath, false, true)
                .AddEnvironmentVariables()
                .Build();

            var sgsConfig = configuration.GetSection("SGSClient");

            //Base url for SGS service
            var _clientConfig = sgsConfig.GetSection("Client").GetChildren();
            var baseAddress = _clientConfig.FirstOrDefault(o => o.Key.Equals("BaseAddress"));
            BaseAddress = new Uri(baseAddress.Value);

            //Adding headers
            DefaultRequestHeaders.Accept.Clear();
            DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            _dateUTC = DateTime.UtcNow.ToString("u");
            DefaultRequestHeaders.Add("DateUtc", _dateUTC);


        }

您可以使用此类型格式发送可能会有帮助

 var postTask = client.PostAsJsonAsync<ClassNameOfObject>(baseUri + "ControllerName/ActionName?UserID=" + UserID, object);
                postTask.Wait();

这个和 one other SO question were the only useful pages I found when I was scratching my head over this same issue today. Neither question had satisfactory explanations though. So after some more head scratching, I was able to set my mind at ease. Hopefully my answer 对另一个问题的解释让您满意!

tl;博士

PostAsJsonAsync 使用 JsonContent ,它使用 Transfer-Encoding: chunked 而不是 Content-Length 并且“奇怪的字符”是块头(并且完全有效 HTTP/1.1 )