【问题标题】:HttpPost Json object property naming behaviorHttpPost Json 对象属性命名行为
【发布时间】:2021-12-19 21:59:02
【问题描述】:

对于 HttpPost 功能

public async Task<Result> PostAsync([FromBody]Request request, [FromHeader(Name = "Cs-Auth")] string authKey=null)
    {
        try{
            HttpResponseMessage response = await httpClient.PostAsJsonAsync(_config.ApiUrl, request);
                          
            response.EnsureSuccessStatusCode();

            string responseText = await response.Content.ReadAsStringAsync();


            Result result = JsonSerializer.Deserialize<Result>(responseText);

            return ProcessResult(result);
        }
        catch(Exception e)
        {
            _logger.LogError(e.ToString());
            throw;
        }
    }

请求类:

    public class Request
    {
        [JsonPropertyName("text")]
        public string Text { get; set; }

        [JsonPropertyName("user_id")]
        public string user_id { get; set; }

        [JsonPropertyName("rule_id")]
        public string PolicyId { get; set; }

        public Policy Policy {get; set;}
    }

Json 主体:

    {
      "text": "sample",
      "user_id": "3455643",
      ...
    }

但是我在 PostAsync 中得到的请求看起来像

我期待的是“文本”,而不是“文本”。

我不想将请求类中的属性名称“文本”更改为“文本”,我需要做什么来定义序列化/反序列化行为?

【问题讨论】:

    标签: c# json asp.net-mvc http-post


    【解决方案1】:

    一切正常,您的调试器只是在更改之前显示数据。在你的调试器中试试这个

    var jsonRequest= JsonConvert.SerializeObject(request);
    
        var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
    
     var response = await client.PostAsync(_config.ApiUrl, content);
    

    json请求

    {
          "text": "sample",
          "user_id": "3455643",
          ...
    }
    

    【讨论】:

    • 谢谢。我认为根本原因是 PostAsJsonAsync()。它将对象转换为 Json,但使用 JsonSerializerDefaults.Web,因此它的行为可能不像我希望的那样。
    • @Daolin 是的,你是对的。我通常不使用 PostAsJsonAsync 。我更喜欢在发送之前显式序列化。
    猜你喜欢
    • 2020-02-02
    • 2012-03-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2018-05-03
    • 2018-12-27
    相关资源
    最近更新 更多