将自定义格式类添加到WebPI Core反馈错误

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

Adding custom format class to WebPI Core feedback error

问题

Visual Studio 2022 + 所有更新。
WebAPI Core (.Net 6)

我有一个简单的模型类:

[Required(ErrorMessage="Name is required")]
public string Name { get; set; }

[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage="Enter a correct email address")]
public string Email { get; set; }

public string Address { get; set; }
public int Age { get; set; }

当我故意执行 Get 操作并留下 EmailAddress 时,模型会报错。如果我不填写名称,也会收到相同的错误。类似于:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-27be45d9cffab14698524a63120a4f88-6bfe2613f2328a42-00",
    "errors": {
        // 所有错误都在这里
    }
}

然后,我实现了这个类:

public class ReformatValidationProblemAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.Result is BadRequestObjectResult badRequestObjectResult)
            if (badRequestObjectResult.Value is ValidationProblemDetails)
            {
                // 引入了我的自定义类来提供错误
            }

        base.OnResultExecuting(context);
    }
}

我发现的问题是属性的错误位于 context.Result.Value 下(这是我在调试时看到的),但在 Visual Studio 中添加相同代码时无法访问。

我该如何获取所有错误并将它们传递给我的自定义类,以便生成符合我的规范的最终 JSON?

请注意,我可以按照我的规范构建类以生成 JSON,但我只需要知道如何提取多个错误,以便我可以相应地显示它们。

英文:

Visual Studio 2022 + all updates.
WebAPI Core (.Net 6)

I have a simple Model class:

`    [Required(ErrorMEssage="NAme is required"]
     public string Name {get; set;}

 [Required(ErrorMessage = "Email is required"]
 [EmailAddress(ErrorMEssage="Enter a correct email address")]
 public string Email {get; set;}

 public string Address {get; set;}
 public int Age {get; set;}`

When i deliberately execute a Get action and leave the EmailAddress out i get an error from the model. If i leave the name out i also receive that error. Similar to

`{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-27be45d9cffab14698524a63120a4f88-6bfe2613f2328a42-00",
"errors": {
   // All errors here
    ]
}
}`

I then implemented this class

`public class ReformatValidationProblemAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        if (context.Result is BadRequestObjectResult badRequestObjectResult)
            if (badRequestObjectResult.Value is ValidationProblemDetails)
            {
                // Introduced my custom class to provide the error
            }

        base.OnResultExecuting(context);
    }
}`

The issue i find is the error for the property is found under context.Result.Value (which is what i see when i debug) which isnt available when I add the same code in Visual Studio.

How could i get all the errors and pass them into my custom class so the end JSON is produced to my specification?

Please note i can build the class to my specification for the JSON but i just need to know how to pull the multiple errors out so i can display it accordingly.

答案1

得分: 0

以下是您要翻译的代码部分:

MyModel.cs

public class MyModel
{
    [Required(ErrorMessage = "姓名是必填项")]
    public string Name { get; set; }

    [Required(ErrorMessage = "电子邮件是必填项")]
    [EmailAddress(ErrorMessage = "请输入正确的电子邮件地址")]
    public string Email { get; set; }
}

ValidationFilterAttribute.cs

public class ValidationFilterAttribute : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            var customErrorMessage = new Dictionary<string, string>();
            foreach (var entry in context.ModelState)
            {
                customErrorMessage.Add(entry.Key, entry.Value.Errors.FirstOrDefault()?.ErrorMessage);
            }
            context.Result = new ObjectResult(customErrorMessage);
        }
    }
    public void OnActionExecuted(ActionExecutedContext context) { }
}

Program.cs

builder.Services.AddScoped<ValidationFilterAttribute>();
builder.Services.Configure<ApiBehaviorOptions>(options
    => options.SuppressModelStateInvalidFilter = true);

Controller

[HttpPost("test")]
[ServiceFilter(typeof(ValidationFilterAttribute))]
public IActionResult Test(MyModel myModel)
{
    return Ok(myModel);
}

希望这些翻译对您有帮助。

英文:

You can try the following code<br>
MyModel.cs

    public class MyModel
    {
        [Required(ErrorMessage = &quot;NAme is required&quot;)]
        public string Name { get; set; }

        [Required(ErrorMessage = &quot;Email is required&quot;)]
        [EmailAddress(ErrorMessage = &quot;Enter a correct email address&quot;)]
        public string Email { get; set; }
    }

ValidationFilterAttribute.cs

    public class ValidationFilterAttribute : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var customErrorMessage=new Dictionary&lt;string, string&gt;();
                foreach (var b in context.ModelState)
                {
                    customErrorMessage.Add(b.Key, b.Value.Errors.FirstOrDefault().ErrorMessage);
                }
                context.Result = new ObjectResult(customErrorMessage);
            }
        }
        public void OnActionExecuted(ActionExecutedContext context) { }
    }

Program.cs

builder.Services.AddScoped&lt;ValidationFilterAttribute&gt;();
builder.Services.Configure&lt;ApiBehaviorOptions&gt;(options
    =&gt; options.SuppressModelStateInvalidFilter = true);

Controller

        [HttpPost(&quot;test&quot;)]
        [ServiceFilter(typeof(ValidationFilterAttribute))]
        public IActionResult test(MyModel myModel)
        {
            return Ok(myModel);
        }

Test Input<br>
将自定义格式类添加到WebPI Core反馈错误<br>
Response<br>
将自定义格式类添加到WebPI Core反馈错误

huangapple
  • 本文由 发表于 2023年6月12日 18:43:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76455862.html
匿名

发表评论

匿名网友

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

确定