ASP.NET CORE 6异常限制软件和验证

发布于 2025-01-23 06:42:19 字数 406 浏览 2 评论 0原文

在ASP.NET Core 6中,我有一个自定义中间件,可以处理返回特定结构的异常:

 services.AddControllers(options => options.Filters.Add(typeof(CustomHttpResponseExceptionFilter)));

效果很好。但是,当一个参数失败时,类似于以下参数验证:

GetSomethingAsync([Required][MinLength(2)]string orderNumber) 

customhttpresponseexceptionfilter未调用。

在哪里可以拦截EG数据注释[必需]的故障?

In ASP.NET Core 6, I have a custom middleware that handles exceptions returning a specific structure:

 services.AddControllers(options => options.Filters.Add(typeof(CustomHttpResponseExceptionFilter)));

Works nicely. However, when an argument fails a param validation like:

GetSomethingAsync([Required][MinLength(2)]string orderNumber) 

the CustomHttpResponseExceptionFilter isn't called.

Where can I intercept a failure for e.g. data annotation [Required]?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不即不离 2025-01-30 06:42:19

您好,您需要自定义 ModelStateInvalidFilter

为此,您可以在程序中实现以下内容

builder.Services.AddControllers().ConfigureApiBehaviorOptions(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        // Expects an instance of IActionResult.
    };
});

。 -errors?view = aspnetcore-6.0#验证 - failure-error-response“ rel =“ nofollow noreferrer”> Microsoft的文档。

Hello you need to customize the behavior of ModelStateInvalidFilter.

To do so, you can achieve that doing the following in your Program.cs

builder.Services.AddControllers().ConfigureApiBehaviorOptions(options =>
{
    options.InvalidModelStateResponseFactory = context =>
    {
        // Expects an instance of IActionResult.
    };
});

You will find more information at Microsoft's documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文