Closed halilkocaoz closed 3 years ago
Bu işlem .NET 5 öncesinde de var, bizim orada custom bir attribute yazma amacımız model valid olmadığı durumda anlamlı bir response vermekti.
public class ValidateModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(new ErrorApiResponse(ResultMessage.InvalidModel));
}
}
}
Evet. ApiController attribute'u .NET Core'un çok daha erken safhalarında geldi. Model validation ise, sanırım daha sonraki release bir versiyonda eklendi diye hatırlıyorum. Fakat şuanda bütün .NET Core tabanlı projelerde kullanılabilir.
yazdığımız action filter ile model valid olmadığında aldığımız response
{
"success": false,
"message": "messages.error.general.invalidModel"
}
Sadece ApiController'ı kullanırsak daha anlaşılır bir response dönebiliriz diye düşündüm.
Merhaba, .NET 5 ile model validation için şimdilik herhangi bir action filter veya farklı bir middleware yazmamıza gerek yok diye düşünüyorum. ValidateModelStateAttribute.cs'ı kaldırarak, sadece request yaparken kullanılan data transfer objelerinin gereksinimlerini belirmemiz, otomatik olarak kontrol edilmesini sağlar.
Küçük bir örnek ile ApiController attribute eklediğimiz zaman model validation ile ilgili bize neler sunduğunu görelim,
Request body:
Http response status code 400 ile birlikte response body:
Bu konuyla alakalı çok uzun bir dokümantasyon var, detayları için isterseniz bunu inceleyebilirsiniz.