Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid model class property error in .net core API

When I send a post method from postman to .net core API with invalid model class property for example model class contain long field but I send string value, I am getting error in postman but I am not getting error in catch method

    [HttpPost]
    public async Task<IActionResult> CalculateFee(CollegeGetModel collegeModel)
    {
        try
        {
            return await _collegeService.CalculateFee(collegeModel);
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

and model class is

public class CollegeGetModel {
   public long Id {get;set;}
   public string Name {get;set;}
}

and the returned error message is

{
"errors": {
    "Id": [
        "Error converting value \"str\" to type 'System.Int64'. Path 'Id', line 2, position 20."
    ]
},
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "0HLTA1MNU7LV5:00000001"
}

I am not getting this error message in controller catch method. How get this error message in controller method?

like image 429
Nithin Mohan Avatar asked Sep 15 '25 00:09

Nithin Mohan


1 Answers

In ASP.NET Core Web API, Model Binding happens before your code in action method executes. Hence, if there is a model state validation error, it results in automatic 400 response code and hence it will not execute your catch block inside the action method.

Refer this link and this for more details.

Edit: Removed link ASP.Net Web Api 2: HTTP Message Lifecycle

UPDATE: You can disable this automatic 400 response by adding following code in Startup.ConfigureServices:

ASP.Net Core 2.1

services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressConsumesConstraintForFormFileParameters = true;
    options.SuppressInferBindingSourcesForParameters = true;
    options.SuppressModelStateInvalidFilter = true;
});

ASP.Net Core 3.1

services.AddControllers()
        .ConfigureApiBehaviorOptions(options =>
        {
            options.SuppressConsumesConstraintForFormFileParameters = true;
            options.SuppressInferBindingSourcesForParameters = true;
            options.SuppressModelStateInvalidFilter = true;
            options.SuppressMapClientErrors = true;
            options.ClientErrorMapping[404].Link =
                "https://httpstatuses.com/404";
        });
like image 101
Bob Ash Avatar answered Sep 16 '25 15:09

Bob Ash