简体   繁体   中英

How to know if RESTful request didn't contain some arguments in ASP.Net Web API 2?

I want my client to be able to sent some data of the model to the web via Restful request. How can I know if not all part of the object is sent?

For example, the request sent only id, datetime_updated but not qty and datetime_updated.

I know that the framework will set the value to the default of its type, so I can check if DateTime wasn't sent (the default value is 1/1/0001 12:00:00AM which have no meaning in my application). But what about int , I can't simply check that if the value is 0 (0 has it meaning).

// Model
namespace TestingAPI.Models
{
    public class Operator
    {
        public int pkey { get; set; }
        public string id { get; set; }
        public int qty {get; set;}
        public DateTime datetime_created { get; set; }
        public DateTime datetime_updated { get; set; }
    }
}
// Controller
namespace TestingApi.Controllers
{
    public class ProcessingPalletController : ApiController
    {
        public Dictionary<string, object> post(Product dataIn)
        {
            // how can I know if not all argument in Product is sent?
        }

    }
}

You can use attribute over your member of model and check Weather you model is valid or not.
Like if you want to make any property require you can use [Required] attribute over you model field.

public class Operator
{
    [Required]
    public int pkey { get; set; }
    public string id { get; set; }
    public int qty {get; set;}
    public DateTime datetime_created { get; set; }
    public DateTime datetime_updated { get; set; }
}

and inside your

public Dictionary<string, object> post(Product dataIn)
{
    if (ModelState.IsValid)
    {
    }

check model is valid or not as above. You can get the error count etc for each model field (property).

You can also create your own attribute and use them. Few examples of custom attribute

  1. http://www.codeproject.com/Articles/301022/Creating-Custom-Validation-Attribute-in-MVC

You can make the optional members nullable:

namespace TestingAPI.Models
{
    public class Operator
    {
        public int pkey { get; set; }
        public string id { get; set; }
        public int? qty {get; set;}
        public DateTime datetime_created { get; set; }
        public DateTime? datetime_updated { get; set; }
    }
}

When the consumer doesn't provide them, the properties will be null.

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