如何在ASP.NET Web API 2中强制JSON请求主体包含某些特定参数
本文关键字:主体 请求 JSON 包含某 参数 ASP NET Web API | 更新日期: 2023-09-27 18:27:12
在我们的项目中,有一个POST方法,它采用如下JSON请求体:
{
"UserId": string,
"Username": string,
"Email": string
}
如果"电子邮件"为空也可以,但我们希望它始终出现在请求正文中。
所以这是可以的:
{
"UserId": "u12324",
"Username": "tmpUser",
"Email": null
}
但这不是:
{
"UserId": "u12324",
"Username": "tmpUser"
}
你有什么想法吗?这可能吗?
您使用的是asp.net-web-api,它根据asp.net web api中的json和XML序列化,使用json.net作为其底层json序列化程序。这个序列化程序允许您指定给定的属性必须存在(可选地为非null)JsonPropertyAttribute.Required
属性设置,该属性设置有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.
以下类使用这些属性:
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; }
}
请注意,如果属性值为null,设置[JsonProperty(Required = Required.Always)]
将导致序列化期间引发异常。
尝试传递对象中的所有参数
示例
[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; }
}