首页 > 解决方案 > 为 POST 和 PUT 请求获取有效负载为空

问题描述

我制作了 POST 和 PUT API,现在我正在做属性验证,

模型

public class Model 
{
    public string user_identifier { get; set; }
    public string name { get; set; }
}

邮递员中的有效载荷

{
    "user_identifier": "1234",
    "name": "abcd"
}

它适用于此,但是当我更改 user_identifier 的类型时,

{
    "user_identifier": 1234,
    "name": "abcd"
}

Postman 为该属性提供了一个自动 400 错误,我不想要,因为我正在做自己的验证,所以,我添加了这个来抑制那些自动 400 响应,

services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});

现在,当我传递有效载荷时,

{
    "user_identifier": 1234,
    "name": "abcd"
}

有效载荷被认为是空的,任何人都可以帮我解决这个问题,而且我认为抑制自动响应并不好,将不胜感激。

提前致谢。

标签: c#asp.net-core.net-core

解决方案


主要问题是,当您的 json 如下所示时,它说的user_identifier是 anint但您说它应该是string.

{
    "user_identifier": 1234,
    "name": "abcd"
}

这是在新创建的 api 项目上返回的错误。

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|8c6385fc-4816d0c11a257a60.",
    "errors": {
        "$.user_identifier": [
            "The JSON value could not be converted to System.String. Path: $.user_identifier | LineNumber: 1 | BytePositionInLine: 27."
         ]
    }
}

一旦您知道这是问题所在(假设您使用的是 ASP.NET Core >= 3.0.0),您会发现JSON 值无法转换为 System.Int32,这解释了它们是如何从 ASP.NET 中的 Json.NET 迁移而来的核心 3.0.0。一种选择是Microsoft.AspNetCore.Mvc.NewtonsoftJson在启动时安装并添加它services.AddControllers().AddNewtonsoftJson();


推荐阅读