【问题标题】:PostAsJsonAsync adding leading character to request bodyPostAsJsonAsync 将前导字符添加到请求正文
【发布时间】:2022-02-01 03:00:40
【问题描述】:

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

99 {

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

"GameReferenceId":"netent_es_starburst",

"CurrencyCode":"EUR",

"LossLimit":100,

“客户端类型”: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);


        }

【问题讨论】:

  • “奇怪的字符”类型问题通常倾向于指向编码不匹配,但我正在努力思考是什么导致这些特定字符出现。目标服务在什么上运行?
  • @TomW .Net Core 2.2
  • 能否包含HttpClient的配置/初始化代码?
  • @scheien 我已经用附加代码更新了问题,
  • 您是否检查过 Fiddler 的请求/响应以查看是否有与编码/内容类型相关的任何内容?

标签: c# httpclient


【解决方案1】:

这和one other SO question 是我今天在同样的问题上摸不着头脑时发现的唯一有用的页面。但这两个问题都没有令人满意的解释。因此,经过更多的挠头后,我可以放心了。希望my answer 对另一个问题的解释令您满意!

tl;博士

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

【讨论】:

    【解决方案2】:

    您可以使用这种类型的格式发送可能会有所帮助

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

    【讨论】:

    • 有什么区别?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多