C
C#2y ago
barcode

.NET 6 ASP.NET API [Answered]

Hello, I am programming a .NET and currently I am using
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations;
[Required], [MaxLength], [MinLength] to validate data transfer objects sent by users in json. I am wondering is there a better way to validate my DTOs, a week ago someone suggested to use FluentAPI, can someone give me advice?
7 Replies
Cisien
Cisien2y ago
I've heard good things about FluentValidator. nothing wrong with data annotations either, if they suit your needs.
barcode
barcode2y ago
Thank you, the main issue I'm having with data annotations is being forced to Errors.ParamName format, I wrote express before I wrote C# and I had more control of the messages it would return, with data annotations I feel like I'm forced to a standard that is annoying to handle in the frontend Is there a way to change that in the annotations? I found some articles on creating custom problem details factories but I'm not sure is it worth the hassle
Cisien
Cisien2y ago
you can disable it and trigger your own model validation
barcode
barcode2y ago
wdym?
Cisien
Cisien2y ago
something like this:
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
then in your controller, you can call ModelState.IsValid and return your own version of the model state errors
barcode
barcode2y ago
Oh I didn't know that Thank you I will try it out
Accord
Accord2y ago
✅ This post has been marked as answered!