首页 > 解决方案 > HttpPost Json 对象属性命名行为

问题描述

对于 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#jsonasp.net-mvchttp-post

解决方案


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

var jsonRequest= JsonConvert.SerializeObject(request);

    var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

 var response = await client.PostAsync(_config.ApiUrl, content);

jsonRequest

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

推荐阅读