简体   繁体   English

将 POST 和 PUT 请求的有效负载设为 null

[英]Getting payload as null for POST and PUT requests

I made POST and PUT APIs and now I am doing attribute validation,我制作了 POST 和 PUT API,现在我正在做属性验证,

Model模型

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

Payload in postman邮递员中的有效载荷

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

It works for this, but when I change the type of user_identifier like,它适用于此,但是当我更改 user_identifier 的类型时,

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

Postman was giving an automatic 400 error for that attribute, which I don't want because I am doing my own validations, so, I added this to suppress those automatic 400 responses,邮递员为该属性提供了一个自动 400 错误,我不想要,因为我正在做我自己的验证,所以,我添加了这个来抑制那些自动 400 响应,

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

Now, when I pass the payload as,现在,当我将有效载荷传递为

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

the payload is considered as null, Can anyone please help me with this problem, and also I think it not good to suppress the automatic responses, an alternative would be appreciated.有效载荷被认为是空的,任何人都可以帮我解决这个问题,而且我认为抑制自动响应不好,另一种方法将不胜感激。

Thanks in advance.提前致谢。

The main problem is that when your json is like the below, it's saying that the user_identifier is an int but you're saying it should be a string .主要问题是,当您的 json 如下所示时,它说user_identifier是一个int但您说它应该是一个string

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

This is the error that gets returned on a newly created api project.这是在新创建的 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."
         ]
    }
}

Once you know that's the problem (assuming you're using ASP.NET Core >= 3.0.0), you can find The JSON value could not be converted to System.Int32 which explains how they moved from Json.NET in ASP.NET Core 3.0.0.一旦您知道这是问题所在(假设您使用的是 ASP.NET Core >= 3.0.0),您会发现JSON 值无法转换为 System.Int32 ,这解释了它们如何从 ASP.NET 中的 Json.NET 移动核心 3.0.0。 One option would be to install Microsoft.AspNetCore.Mvc.NewtonsoftJson and add it in startup services.AddControllers().AddNewtonsoftJson();一种选择是安装Microsoft.AspNetCore.Mvc.NewtonsoftJson并将其添加到启动services.AddControllers().AddNewtonsoftJson();

In ASP.NET Core 3.0 and later versions, the default JSON serializer is System.Text.Json .在 ASP.NET Core 3.0 及更高版本中, 默认的 JSON 序列化程序是 System.Text.Json

And in following doc, we can find that System.Text.Json does not support Non-string values for string properties , which cause this issue.在下面的文档中,我们可以发现System.Text.Json不支持字符串属性的非字符串值,这导致了这个问题。

https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to?pivots=dotnet-core-3-1#non-string-values-for-string-properties https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to?pivots=dotnet-core-3-1#non-string-字符串属性值

To allow non-string JSON values for string properties in ASP.NET Core 3+ project, as @Shoejep mentioned, we can add Newtonsoft.Json (Json.NET) support in our project by installing the Microsoft.AspNetCore.Mvc.NewtonsoftJson package and updating Startup.ConfigureServices to call AddNewtonsoftJson method.为了在 ASP.NET Core 3+ 项目中允许字符串属性的非字符串 JSON 值,正如@Shoejep 提到的,我们可以通过安装Microsoft.AspNetCore.Mvc.NewtonsoftJson包在我们的项目中添加 Newtonsoft.Json (Json.NET) 支持并更新Startup.ConfigureServices以调用AddNewtonsoftJson方法。

https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-5.0&tabs=visual-studio#use-newtonsoftjson-in-an-aspnet-core-30-mvc-project https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-5.0&tabs=visual-studio#use-newtonsoftjson-in-an-aspnet-core-30 -mvc-项目

Thanks for all the help everyone.谢谢各位的帮助。

I was not able to find a way to validate the attribute so that .Net doesn't give an automatic 400 BadRequest response.我无法找到验证属性的方法,因此 .Net 不会自动提供400 BadRequest响应。

I figured out the problem, this was happening because I was getting the payload using [FromBody] PayloadModel payload in the parameter of Post request.我发现了这个问题,这是因为我在 Post 请求的参数中使用[FromBody] PayloadModel payload载荷来获取有效载荷。

Now, I have changed my approach to take the payload using,现在,我已经改变了使用有效载荷的方法,

var streamReader = new StreamReader(Request.Body);
string requestBody = await streamReader.ReadToEndAsync();
var payload = JsonConvert.DeserializeObject<PayloadModel>(requestBody);

And modified my model class to,并将我的模型类修改为,

public class PayloadModel 
{
    [JsonProperty("user_identifier")]
    public string UserIdentifier { get; set; }
    
    [JsonProperty("name")]
    public string name { get; set; }
}

This way, I have a bit more granular level control on payload validation.通过这种方式,我可以对有效负载验证进行更精细的级别控制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM