Dotnet 3.0.103 - JsonConvert.DeserializeObject 期望转义良好的字符串,而不是普通的 Json

Dotnet 3.0.103 - JsonConvert.DeserializeObject expects well escaped string as opposed to a plain Json

我使用的是 Dotnet 3.0.103。我公开了一个 webapi,它有这样定义的代码,

[HttpPost]
        public string Post([FromBody] string data)
        {
            try
            {
            EmployeeRequest request = JsonConvert.DeserializeObject<EmployeeRequest>(data);

现在,当我从我的邮递员那里调用 API 时,像这样的正常 json 请求正文不起作用

{"EmployeeId": 3, "Name": "John"}

它会抛出这样的错误,

{
    "errors": {
        "": [
            "Unexpected character encountered while parsing value: {. Path '', line 1, position 1."
        ]
    },
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|b9ea70ff-4ffda7ef1c244839."
}

作为转义字符串而不是 Json 正文可以正常工作,

 "{\"EmployeeId\": 3, \"Name\": \"John\"}"

我想让它只用普通的 json。

感谢任何帮助。

谢谢, 阿伦

您不需要单独反序列化 json。 .NET 可以开箱即用地为您做到这一点。 尝试将签名更改为:public string Post([FromBody] EmployeeRequest data) 并在不转义的情况下从邮递员处拨打电话。应该可以。

ASP.Net 的模型绑定可以自动将 JSON 负载绑定到您的 Action 参数。因此,您应该能够取消手动反序列化:

[HttpPost]
public string Post([FromBody]EmployeeRequest request)
{
    // request should be properly populated