在C# WebAPI中如何捕获验证错误。

huangapple go评论70阅读模式
英文:

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&lt;ApiBehaviorOptions&gt;(options =&gt;
{
    options.SuppressModelStateInvalidFilter = true;
});

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

huangapple
  • 本文由 发表于 2023年5月13日 14:54:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定