kwv84
kwv84

Reputation: 953

Validate Web Api 2 data before saving it to the database

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

Answers (2)

blogbydev
blogbydev

Reputation: 1495

Server Validation can be done in 2 ways

  1. Data Attribute based validation
  2. 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

kamil-mrzyglod
kamil-mrzyglod

Reputation: 5008

You should validate your data on all level, that means:

  • on front-end(to increase UX and application responsiveness)
  • on data binding(to make sure that passed data is valid)
  • after receiving it on other level(business validation etc.)
  • on storing it(proper column types, lengths, keys e.g.)

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

Related Questions