gpt4 book ai didi

c# - 覆盖 ModelState 的非常技术性的错误消息

转载 作者:太空宇宙 更新时间:2023-11-03 10:27:21 27 4
gpt4 key购买 nike

我有以下代码:

public class EventController : ApiController
{
public IHttpActionResult Post(List<Event> Events)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
else
{
foreach (Event Event in Events)
{
Debug.WriteLine(Event.Importance.ToString());
Debug.WriteLine(Event.Date.ToString());
Debug.WriteLine(Event.Description);
}
return Ok();
}
}
}

public class Event
{
[DataAnnotationsExtensions.Integer(ErrorMessage = "{0} must be a number.")]
[Range(0,10),Required()]
public int? Importance { get; set; }

public DateTime Date { get; set; }

[RegularExpression(@"^.{20,100}$", ErrorMessage="{0} must be between 20 and 100 characters.")]
public string Description { get; set; }
}

我将发布以下 JSON:

[{"Importance":"1.1","Date":"2015-03-12","Description":""},{"Importance":"6","Date":"2015-10-02","Description":"a"}]

响应是:

{
"Message": "The request is invalid.",
"ModelState": {
"Events[0].Importance": [
"Could not convert string to integer: 1.1. Path '[0].Importance', line 1, position 20.",
"The Importance field is required."
],
"Events[1].Description": [
"Description must be between 20 and 100 characters."
]

}

我担心“无法将字符串转换为整数:1.1。路径‘[0].Importance’,第 1 行,位置 20。”我想用更友好、更不暴露的内容来覆盖此消息,也许是“重要性必须是一个数字”。理想情况下,我想在 DataAnnotation 中定义默认转换错误。我尝试使用此处找到的 DataAnnotationsExtensions Nuget http://dataannotationsextensions.org/不幸的是,这针对 MVC,并且不会覆盖 ModelState 错误。如果无法覆盖,我很好奇常见的解决方法是什么。

最佳答案

一个解决方案(我不太喜欢)是使用对象类型而不是 int?输入:

public class Event
{
[DataAnnotationsExtensions.Integer(ErrorMessage = "{0} must be a number.")]
[Range(0,10),Required()]
public object Importance { get; set; }

...
}

如果您这样做,转换默认消息将被覆盖。

关于c# - 覆盖 ModelState 的非常技术性的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31278623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com