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

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

Adding custom format class to WebPI Core feedback error

问题

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

我有一个简单的模型类:

  1. [Required(ErrorMessage="Name is required")]
  2. public string Name { get; set; }
  3. [Required(ErrorMessage = "Email is required")]
  4. [EmailAddress(ErrorMessage="Enter a correct email address")]
  5. public string Email { get; set; }
  6. public string Address { get; set; }
  7. public int Age { get; set; }

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

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

然后,我实现了这个类:

  1. public class ReformatValidationProblemAttribute : ActionFilterAttribute
  2. {
  3. public override void OnResultExecuting(ResultExecutingContext context)
  4. {
  5. if (context.Result is BadRequestObjectResult badRequestObjectResult)
  6. if (badRequestObjectResult.Value is ValidationProblemDetails)
  7. {
  8. // 引入了我的自定义类来提供错误
  9. }
  10. base.OnResultExecuting(context);
  11. }
  12. }

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

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

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

英文:

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

I have a simple Model class:

  1. ` [Required(ErrorMEssage="NAme is required"]
  2. public string Name {get; set;}
  3. [Required(ErrorMessage = "Email is required"]
  4. [EmailAddress(ErrorMEssage="Enter a correct email address")]
  5. public string Email {get; set;}
  6. public string Address {get; set;}
  7. 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

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

I then implemented this class

  1. `public class ReformatValidationProblemAttribute : ActionFilterAttribute
  2. {
  3. public override void OnResultExecuting(ResultExecutingContext context)
  4. {
  5. if (context.Result is BadRequestObjectResult badRequestObjectResult)
  6. if (badRequestObjectResult.Value is ValidationProblemDetails)
  7. {
  8. // Introduced my custom class to provide the error
  9. }
  10. base.OnResultExecuting(context);
  11. }
  12. }`

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

  1. public class MyModel
  2. {
  3. [Required(ErrorMessage = "姓名是必填项")]
  4. public string Name { get; set; }
  5. [Required(ErrorMessage = "电子邮件是必填项")]
  6. [EmailAddress(ErrorMessage = "请输入正确的电子邮件地址")]
  7. public string Email { get; set; }
  8. }

ValidationFilterAttribute.cs

  1. public class ValidationFilterAttribute : IActionFilter
  2. {
  3. public void OnActionExecuting(ActionExecutingContext context)
  4. {
  5. if (!context.ModelState.IsValid)
  6. {
  7. var customErrorMessage = new Dictionary<string, string>();
  8. foreach (var entry in context.ModelState)
  9. {
  10. customErrorMessage.Add(entry.Key, entry.Value.Errors.FirstOrDefault()?.ErrorMessage);
  11. }
  12. context.Result = new ObjectResult(customErrorMessage);
  13. }
  14. }
  15. public void OnActionExecuted(ActionExecutedContext context) { }
  16. }

Program.cs

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

Controller

  1. [HttpPost("test")]
  2. [ServiceFilter(typeof(ValidationFilterAttribute))]
  3. public IActionResult Test(MyModel myModel)
  4. {
  5. return Ok(myModel);
  6. }

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

英文:

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

  1. public class MyModel
  2. {
  3. [Required(ErrorMessage = &quot;NAme is required&quot;)]
  4. public string Name { get; set; }
  5. [Required(ErrorMessage = &quot;Email is required&quot;)]
  6. [EmailAddress(ErrorMessage = &quot;Enter a correct email address&quot;)]
  7. public string Email { get; set; }
  8. }

ValidationFilterAttribute.cs

  1. public class ValidationFilterAttribute : IActionFilter
  2. {
  3. public void OnActionExecuting(ActionExecutingContext context)
  4. {
  5. if (!context.ModelState.IsValid)
  6. {
  7. var customErrorMessage=new Dictionary&lt;string, string&gt;();
  8. foreach (var b in context.ModelState)
  9. {
  10. customErrorMessage.Add(b.Key, b.Value.Errors.FirstOrDefault().ErrorMessage);
  11. }
  12. context.Result = new ObjectResult(customErrorMessage);
  13. }
  14. }
  15. public void OnActionExecuted(ActionExecutedContext context) { }
  16. }

Program.cs

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

Controller

  1. [HttpPost(&quot;test&quot;)]
  2. [ServiceFilter(typeof(ValidationFilterAttribute))]
  3. public IActionResult test(MyModel myModel)
  4. {
  5. return Ok(myModel);
  6. }

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:

确定