ASP.NET Core:防止针对单个操作的自动HTTP 400响应 [英] ASP.NET Core: Prevent Automatic HTTP 400 responses for individual action
问题描述
我喜欢自动HTTP 400响应是ASP.NET Core 2.1的新增功能,并且在大多数情况下效果都很好.
但是,在一项操作中,我需要在验证有效负载之前进行一些预处理.我有一个自定义验证器,该验证器需要模型中的两个值来执行验证.这些值之一在路径中,因此我想从路径上在模型上设置该值,然后进行验证.
我不想使用以下所有操作关闭功能:
public void ConfigureServices(IServiceCollection服务){services.Configure< ApiBehaviorOptions>(options =>{options.SuppressModelStateInvalidFilter = true;});}
有什么办法可以将其关掉吗?
我尝试修改InvalidModelStateResponseFactory,但是它没有解决我的问题,因为我仍然需要执行控制器操作:
services.Configure< ApiBehaviorOptions>(options =>{options.InvalidModelStateResponseFactory = actionContext =>{var ignore = actionContext.ActionDescriptor.FilterDescriptors.Any(fd => fd.Filter是SuppressModelStateInvalidFilterAttribute);如果(忽略){//只能返回IActionResult,因此不输入控制器操作.}返回新的BadRequestObjectResult(actionContext.ModelState);};});[AttributeUsage(AttributeTargets.Method)]公共类SuppressModelStateInvalidFilterAttribute:FormatFilterAttribute{}
这里是我在asp.net核心存储库上提出的一个问题的链接,以防万一,我可以找到它-解决方案
这可以通过针对特定情况实现自己的验证器来解决.文档中对此进行了很好的介绍.
要么验证模型绑定器,要么创建定制模型绑定器,以在验证之前完成所有预处理.
I like the Automatic HTTP 400 responses functionality new to ASP.NET Core 2.1 and it's working out really well for most cases.
However, in one action I need to do a bit of pre-processing before validation the payload. I have a custom validator that requires two values in the model to perform validation. One of those values is in the path so I would like to set that value on the model from the path then validate.
I don't want to switch the functionality off for all actions with:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
}
Is there any way I could switch it off just for an individual action?
Edit:
I tried modifying the InvalidModelStateResponseFactory but it didn't solve my problem because I still need to get into the controller action:
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = actionContext =>
{
var ignore = actionContext.ActionDescriptor.FilterDescriptors.Any(fd => fd.Filter is SuppressModelStateInvalidFilterAttribute);
if (ignore)
{
// Can only return IActionResult so doesn't enter the controller action.
}
return new BadRequestObjectResult(actionContext.ModelState);
};
});
[AttributeUsage(AttributeTargets.Method)]
public class SuppressModelStateInvalidFilterAttribute : FormatFilterAttribute
{
}
Edit:
Here's a link to an issue I raised on the asp.net core repo in case I get anywhere with that - https://github.com/aspnet/Mvc/issues/8575
This could probably be solved by implementing your own validator for your specific case. It is covered quite well in the documentation.
Either that or possibly a custom model binder to create your model with all the preprocessing done before it is validated.
这篇关于ASP.NET Core:防止针对单个操作的自动HTTP 400响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!