Tu Anh
Tu Anh

Reputation: 367

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?

Upvotes: 0

Views: 1711

Answers (2)

dbc
dbc

Reputation: 117274

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.

Upvotes: 3

arpan
arpan

Reputation: 1

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

Upvotes: -1

Related Questions