【发布时间】:2019-01-20 07:37:53
【问题描述】:
我有一个 .Net WebAPI 项目,它从多个客户端接收数据对象并对其进行处理。
我想确保 JSON 消息确实包含所有必填字段。
为了确保这一点,我为所有必须由客户端设置的属性添加了Required 属性 (System.ComponentModel.DataAnnotations)。
当我检查ModelState.IsValid 时这工作正常,但现在我想抛出一个有用的BadRequest,它应该包含Required 属性中设置的ErrorMessage。
型号
public class DataModel
{
[Required(ErrorMessage = "ExampleProperty is required!")]
public string ExampleProperty { get; set; }
}
控制器
public class DataController
{
public DataModel PostData(DataModel data)
{
if (ModelState.IsValid)
{
// This part is working fine..
return ProcessData(data);
}
else
{
// errs do only contain Exception.Messages not ErrorMessages..
string errs = string.Join(
"\n",
ModelState.Values
.SelectMany(s => s.Errors)
.Select(e => string.IsNullOrWhiteSpace(e.ErrorMessage) ? (e.Exception != null ? e.Exception.Message : null) : e.ErrorMessage)
.Where(s => !string.IsNullOrWhiteSpace(s))
.GroupBy(g => g).Select(s => s.Key + " (#" + s.Count() + ")"));
throw new Exception("...todo: fill in correct text...");
}
}
}
ModelState.Values.First().Errors
- 异常包含:“在 JSON 中找不到必需的属性 'ExampleProperty'。路径 [...]”
- 但是 ErrorMessage 是空的。
有什么想法会导致这种情况吗?我做错了什么?
【问题讨论】:
-
我试过了,得到了相同的 XML 输出,但
errs包含预期的错误消息,不知道为什么它会失败。也许再试一次。关于 XML 输出试试这个:stackoverflow.com/questions/8112892/… -
@jps 谢谢! Xml 序列化错误。我进行了调试 webapi 的设置并手动查看了
errors。异常设置正确,但ErrorMessage不包含我在属性中设置的文本...
标签: c# asp.net-web-api error-handling data-annotations modelstate