![](/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.