自定义结果过滤器 vs InvalidModelStateResponseFactory 在 ASP.NET Core 6.0 中

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

Custom result filter vs InvalidModelStateResponseFactory in ASP.NET Core 6.0

问题

You can use a custom result filter inherited by IResultFilter to return a response in case of a model-validation failure. Alternatively, you can configure ApiBehaviorOptions in Program.cs to handle invalid model states.

Scenario for Using a Custom Result Filter (FailedValidationResultFilter):

  • Pros: This approach allows for more fine-grained control over how validation failures are handled. You can implement custom logic inside the FailedValidationResultFilter to create a ProblemDetails response tailored to your specific needs. It's particularly useful when you have complex validation requirements.

  • Cons: Requires additional code and might be more suitable for advanced scenarios.

Scenario for Using ApiBehaviorOptions in Program.cs:

  • Pros: This approach is simpler and requires less custom code. It leverages the built-in ApiBehaviorOptions configuration to handle validation errors consistently across the application.

  • Cons: It may offer less flexibility compared to a custom result filter if you have highly specific requirements for handling validation failures.

Ultimately, the choice between these two approaches depends on your project's needs:

  • If you need precise control over the response generation for model-validation failures and have complex requirements, the custom result filter (FailedValidationResultFilter) is a better choice.

  • If you prefer a simpler and more consistent approach for handling validation errors throughout your application, using ApiBehaviorOptions in Program.cs is a more straightforward option.

Consider your project's complexity and requirements to decide which approach aligns better with your development goals.

英文:

I can use a custom result filter inherited by IResultFilter to return response in case of a model-validation failure:

public class FailedValidationResultFilter : IResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.ModelState.IsValid)
            return;

        //other logic to create the ProblemDetails response
    }

    public void OnResultExecuted(ResultExecutedContext context)
    {
    }
}

Or I can use this in Program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Services
    .AddControllers();
builder.Services
    .Configure<ApiBehaviorOptions>(x => x.InvalidModelStateResponseFactory = ctx => new ValidationProblemDetailsResult(););

ValidationProblemDetailsResult:

public class ValidationProblemDetailsResult : IActionResult
{
    public async Task ExecuteResultAsync(ActionContext context)
    {
        //logic here and then followed by this:
        var problemDetails = new ProblemDetails
		{
    		Type = "",
	    	Title = "Invalid parameters",
		    Status = StatusCodes.Status400BadRequest,
		    Detail = "Your request parameters didn't validate.",
		    Instance = "",
		    //Extensions = 
	    };

	    var objectResult = new ObjectResult(problemDetails) { StatusCode = problemDetails.Status };
		await objectResult.ExecuteResultAsync(context);
    }
}

Question: which one should I prefer and why? Also, please provide scenario(s), to better understand their uses/pros and cons.

答案1

得分: 1

在 WeiApi 项目中,[ApiController] 属性会使模型验证错误自动触发 HTTP 400 响应。

你的代码如下:

builder.Services.Configure<ApiBehaviorOptions>(x => x.InvalidModelStateResponseFactory = ctx => new ValidationProblemDetailsResult());

该代码替换了默认的 BadrequestResult,当它自动触发 400 响应时(换句话说,仅当你的控制器附带 [ApiController] 属性并应用于控制器中的所有操作时),你可以查看这个相关的文档

通过使用过滤器,你可以选择将其应用于特定的控制器/操作或所有操作,无论控制器是否附带 ApiControoler 属性,有关此内容可以查看文档

英文:

In WeiApi projects,the [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response.

and your codes

builder.Services
    .Configure&lt;ApiBehaviorOptions&gt;(x =&gt; x.InvalidModelStateResponseFactory = ctx =&gt; new ValidationProblemDetailsResult();); 

replaced the default BadrequestResult with your custom result,when it trigger 400 resopnse automaticlly(In an other words,it works only when your controller is attached with [ApiController] attribute and applied to all actions in the controller ) ,you could check this document related

With a filter,you could choose to apply it to certain controller/action or all actions whenever the controller is attached with ApiControoler Attribute or not,the document related

huangapple
  • 本文由 发表于 2023年6月6日 00:34:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408408.html
匿名

发表评论

匿名网友

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

确定