英文:
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
英文:
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
答案1
得分: 0
对于ASP.NET Core 2.1或更高版本,使用[ApiController]属性的Web API控制器,模型状态验证会自动发生。
要关闭此过滤器,请在Program.cs中添加以下内容:
builder.Services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
参考链接:
https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-7.0
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论