ASP.NET Core 错误 : The JSON value could not be converted to System. 字符串

标签 asp.net json asp.net-mvc asp.net-core

我正在尝试在 ASP.NET Core 中执行搜索功能。这是我的 Controller :

[HttpPost("searchbyname")]
   public async Task<ActionResult<List<SelectedChildDto>>> SearchByName([FromBody]string firstName)
   { if (string.IsNullOrWhiteSpace(firstName)) { return new List<SelectedChildDto>(); }
            return await _context.Children
                .Where(x => x.FirstName.Contains(firstName))
                .OrderBy(x => x.FirstName)
                .Select(x => new SelectedChildDto { Cld = x.Cld, ChildCode = x.ChildCode, 
                 FirstName = x.FirstName, PhotoPath = x.PhotoPath })
                .Take(5)
               .ToListAsync();               
              
        }

我从模型中有这个 DTO 类

namespace API.Dtos
{
    public class SelectedChildDto
    {
      
        public int Cld { get; set; }

        public string ChildCode { get; set; }
     
        public string FirstName { get; set; }
         public string PhotoPath { get; set; }
    }
}

这是我的错误输出:

"errors": {
        "$": [
            "The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
        ]
    }

我该如何解决这个问题?

最佳答案

该问题与 Controller 的单个 [FromBody] string firstName 参数的正文文本的 System.Text.Json 反序列化有关。例如,您只需在正文中发送 "John",而不是完整功能的 JSON {"firstName": "John"}

另请检查this answer类似的问题。

关于ASP.NET Core 错误 : The JSON value could not be converted to System. 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72385282/

相关文章:

c# - 自定义sql查询

c# - ASP.NET:同步客户端和服务器端验证规则

c# - 如何在 ASP.NET 中按类而不是 ID 选择元素?

ASP.NET:响应中的全局 Hook ?

css - 编写非常大的级联样式表 (CSS) 文件的最佳方法是什么

javascript - 从 yii 中的不同表中搜索

javascript - lowdb 添加/编辑/更新/删除成功,但需要使用 if/then/else 语句对更新部分进行一些更改

json - RESTful HTTP API标准?

javascript - 将列表的元组设置为 ViewData Mvc C#

c# - 具有多态对象集合的复杂模型的自定义模型绑定(bind)器