Invalid Model Class Property Error In. Net Core Api

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?

2

2 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 =
                "";
        });
3

In ASP.NET core Web API, any invalid model binding are stored in ModelState property. However, AspNet core automatically return Bad Request if ModelState are invalid by using ApiController attribute on top of your Controller class.

To intercept the request, you have to comment out the ApiController attribute.

[Route("api/[controller]")]
//[ApiController]
public class HomeController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CalculateFee(CollegeGetModel collegeModel)
    {
        if (!ModelState.IsValid)
        {
            // Do whatever you want here. E.g: Logging
        }
        return await _collegeService.CalculateFee(collegeModel);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.