Search code examples
c#asp.net-coreasp.net-core-webapirestsharp

How do I catch validation error in C# WebAPI


I have a C# Web API. It has a controller which has a POST method in it. The model class I pass has some data annotations (e.g. Required, MaxLength, etc).

I am calling it from a client using RestSharp.

Any time there is some kind of problem, I just get a generic error message on the client side:

The JSON value could not be converted to System.Collections.Generic.List`1[PDS.Core.Types.ResponseDtos.ErrorCode]....

Wouldn't be a problem, but on the server side when I put a breakpoint into the method it doesn't hit the breakpoint. So I am assuming the error is being thrown by the validation (or something else).

So my question is, how do I find out what the problem is? I can't debug the code since it's not hitting the breakpoint. Is there some kind of interceptor I can put on the server side so I can at least see some kind of error message?

Thanks


Solution

  • For ASP.NET Core 2.1 or later, Web API controllers using [ApiController] attribute, model state validation occurs automatically.

    To turn off this filter, add this to your Program.cs:

    builder.Services.Configure<ApiBehaviorOptions>(options =>
    {
        options.SuppressModelStateInvalidFilter = true;
    });
    

    Reference: https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-7.0