Reputation: 953
I'm not sure if this is the correct place to ask this question but here is the thing.
I'm creating a Web API 2 webservice where an external application can post data. Before the data is saved to the database I want to validate my data (are all required fields entered, etc.). The datamodel I have to use, does accept any string as itemNumber, so I want to make sure the data is correct. In this case:
To approach this I have the following (simplified) model to receive data from the POST.
public class Product {
public int ID { get; set; }
[RequiredItem]
public string ItemNumber { get; set; }
[RequiredDelivery]
public string DeliveryType { get; set; }
}
My custom attribute 'RequiredItem' is checking the database if the item exists in the database. If not, the response will be a Json message that you need to provide a valid itemnumber.
The attribute 'RequiredDelivery' checks if the combination ItemNumber / DeliveryType is a valid combination (by checking a table where all combinations are stored).
When all the data is correct, I map it to the database model (EF) en write the data to the database.
My question is, if this is a good approach to validate the POST data, or should I do that on an other level?
Upvotes: 1
Views: 820
Reputation: 1495
Server Validation can be done in 2 ways
IValidatableObject
. A general way to have this approach is, create a DTO class(Data Transfer Object) that will contain all the input fields from the user. Create a factory that will convert this DTO into required model(the object that you will use to store data in database). Implement IValidatableObject
interface for your DTO class. Now, before the request goes into your Controller action, the Validate
method of IValidatableObject
will be called. I would prefer this approach over Data Attribute based validation when i need more control over validation.Then make a validation filter, to return the modelstate that will contain errors with proper status code.
Upvotes: 1
Reputation: 5008
You should validate your data on all level, that means:
Remember not to trust any data which comes from user(or outside your API in general).
Basically what I have heard, validation should be performed for each layer/level your system has.
Upvotes: 0