简体   繁体   中英

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:

{
"UserId": string,
"Username": string,
"Email": string
}

It's ok if "Email" is null but we want it to always present in the request body.

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 , which uses as its underlying JSON serializer, according to JSON and XML Serialization in ASP.NET Web API . 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 :

 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.

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; }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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