[英]How to force JSON request body to contain some specific parameter in ASP.NET Web API 2
In our project, there is a POST method which take a JSON request body like this: 在我们的项目中,有一个POST方法,它采用这样的JSON请求正文:
{
"UserId": string,
"Username": string,
"Email": string
}
It's ok if "Email" is null but we want it to always present in the request body. 可以将“ Email”为空,但我们希望它始终出现在请求正文中。
So this is OK: 这样就可以了:
{
"UserId": "u12324",
"Username": "tmpUser",
"Email": null
}
but this is not: 但这不是:
{
"UserId": "u12324",
"Username": "tmpUser"
}
Do you have any ideas? 你有什么想法? Is it even possible? 可能吗?
You are using asp.net-web-api , which uses json.net as its underlying JSON serializer, according to JSON and XML Serialization in ASP.NET Web API . 根据ASP.NET Web API中的JSON和XML序列化,您正在使用asp.net-web-api ,它将json.net用作其底层JSON序列化器 。 This serializer allows you to specify that a given property must be present (and optionally non-null) with the JsonPropertyAttribute.Required
attribute setting, which has 4 values : 该序列化程序允许您使用JsonPropertyAttribute.Required
属性设置指定给定的属性必须存在(并且可以选择为非null),该属性设置具有4个值 :
Default The property is not required. The default state. AllowNull The property must be defined in JSON but can be a null value. Always The property must be defined in JSON and cannot be a null value. DisallowNull The property is not required but it cannot be a null value.
The following class makes use of these attributes: 下面的类使用这些属性:
public class EmailData
{
[JsonProperty(Required = Required.Always)] // Must be present and non-null
public string UserId { get; set; }
[JsonProperty(Required = Required.Always)] // Must be present and non-null
public string Username { get; set; }
[JsonProperty(Required = Required.AllowNull)] // Must be present but can be null
public string Email { get; set; }
}
Note that setting [JsonProperty(Required = Required.Always)]
will cause an exception to be thrown during serialization if the property value is null. 请注意,如果属性值为null,则设置[JsonProperty(Required = Required.Always)]
将导致在序列化期间引发异常。
Try to pass all parameters in a object 尝试传递对象中的所有参数
Example 例
[HttpPost]
public bool Create(DoSomething model)
{
return true
}
public class DoSomething
{
public int UserId{ get; set; }
public string UserName{ get; set; }
public string Email{ get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.