英文:
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 = "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; }
}
ValidationFilterAttribute.cs
public class ValidationFilterAttribute : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var customErrorMessage=new Dictionary<string, string>();
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<ValidationFilterAttribute>();
builder.Services.Configure<ApiBehaviorOptions>(options
=> options.SuppressModelStateInvalidFilter = true);
Controller
[HttpPost("test")]
[ServiceFilter(typeof(ValidationFilterAttribute))]
public IActionResult test(MyModel myModel)
{
return Ok(myModel);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论