Search code examples
c#apivalidationactionfilterattributeexceptionfilterattribute

API Filters and Validation


Is it best to do all validation in filters (i.e. ActionFilterAttribute) before the main work begins?

In my application I have to validate the data in a URL, such as date validation, is it a number, is the incoming URL from an allowed device and Base64 authorization. From there the data is upserted to do a DB. It currently works but I do all the validation in the end point, but I would like to improve things.

In summary, should I use filters to do the upfront validation, then move to the main endpoint and complete the insert of data. What are the main advantages and disadvantages?

I have been doing some research on filters, but I have not found anything that says explicitly to use them for full validation. It seems that using filters would be the best way to do validation.


Solution

  • You could use filters for validations not specific to any component, or some validation that must be done before any work, that way you can reuse those filters in multiple actions.

    For data validation related to a specific functionality, it's better to let the appropriate action to handle it, or else you would end with a bunch of filters.

    Put simply:

    • Use filters to: validate incoming URL from an allowed device and Base64 authorization.

    • Use actions to: validate parameters (i.e, date, numbers, etc)