![](/img/trans.png)
[英]How to know if RESTful request didn't contain some arguments in ASP.Net Web API 2?
[英]How to force JSON request body to contain some specific parameter in ASP.NET Web API 2
在我们的项目中,有一个POST方法,它采用这样的JSON请求正文:
{
"UserId": string,
"Username": string,
"Email": string
}
可以将“ Email”为空,但我们希望它始终出现在请求正文中。
这样就可以了:
{
"UserId": "u12324",
"Username": "tmpUser",
"Email": null
}
但这不是:
{
"UserId": "u12324",
"Username": "tmpUser"
}
你有什么想法? 可能吗?
根据ASP.NET Web API中的JSON和XML序列化,您正在使用asp.net-web-api ,它将json.net用作其底层JSON序列化器 。 该序列化程序允许您使用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.
下面的类使用这些属性:
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.