(blog | rss | twitter | linkedin)
There are various techniques for validating requests in ASP.NET Core Web APIs. Here is a quick recap:
For simple DTO/REST model validation, you can use attributes like [Required]
, [Email]
etc from the System.ComponentModel.DataAnnotation namespace (more details here).
You can set up custom model validation.
For other miscellaneous validation (e.g. JWT validation), you can set up middleware. Several 1st & 3rd party nuget packages are available for these, I generally use the built-in Microsoft.AspNetCore.Authentication.JwtBearer library.
You can also set up route constraints like {id:int}
, {name:required}
, {weight:float}
etc. Strictly speaking, they aren’t for validation but for route disambiguation.
You can use 3rd party libraries like FluentValidation to set up validation rules. FluentValidation middleware is executed before any of the above (More details here). Maybe I should write a blog post soon on this.
PS: This blog post emanated from a discussion on a slack channel. Thought I should capture it in case anyone else finds it useful. Did I get something wrong? Or miss out on some details? Would love to hear from you, please leave a comment below or send me a tweet.
That’s it for today folks!