【问题标题】:Model validation not returning correct error message in Web API模型验证未在 Web API 中返回正确的错误消息
【发布时间】:2018-08-03 21:13:58
【问题描述】:

我有一个模型 (myModel),在 myProperty 上有以下数据注释

[Required(ErrorMessage = "myProperty is required.")]

在 api 控制器中,我们按如下方式验证模型:

  if (!ModelState.IsValid)
{



   var errorResponse = new HttpRequestMessage()
.CreateErrorResponse(HttpStatusCode.BadReques, ModelState);

    throw new HttpResponseException(errorResponse);
}

我在邮递员中得到的是:

    {
    "Message": "The request is invalid.",
    "ModelState": {
        "myModel": [
            "An error has occurred."
        ]
    }
}

我想从数据注释中取回错误消息。

【问题讨论】:

  • 你不能把它放在控制器的响应消息中
  • 抛出新的 HttpResponseException(errorResponse);发生在该行号
  • 这不是我的目标——我想让机制从数据注释返回消息是模型
  • 嗯。是的,如果您想在响应中发送该消息,则 dtata 注释会使用 javascript 验证在 mvc 中显示这些消息我很确定唯一的方法是在出现错误时将其包含在响应中。

标签: asp.net validation asp.net-web-api c#-4.0 asp.net-web-api2


【解决方案1】:

例如,您的模型应该是这样的

[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string  EmailAddress { get; set; }  

还有你的行动方法

if (!ModelState.IsValid) {
    var error = ModelState.Where(e => e.Value.Errors.Count > 0).Select(e => new { Name = e.Key, Message = e.Value.Errors.First().ErrorMessage }).ToList();
    return Request.CreateResponse(HttpStatusCode.BadRequest, new Dictionary<string, object>()
    {
        { "ErrorList", error }
    });
}

【讨论】:

  • 您从必需数据注释中遗漏了 ErrorMessage - 类似于:[Required(ErrorMessage = "This is the error I would want to see returned to postman")]
  • 感谢@Jim Evans 的更正,但谦虚地说,如果我没有设置 ErrorMessage,那么它将提供类似这样的默认消息 { "ErrorList": [ { "Name": "EmailAddress", "Message": "EmailAddress 字段是必需的。" } ] }
  • 我很欣赏这些信息,但我的任务是获取返回的数据注释错误消息。感谢您的意见。
【解决方案2】:

您可以从ModelState.Errors 属性中获取模型状态验证的错误消息,它是ModelError 的集合。

MSDN documentation

【讨论】:

  • 感谢您的回复。试过了,但它只包含默认错误“在 JSON 中找不到所需的属性'myProperty'。路径'',第 23 行,位置 1。”而不是数据注释中定义的消息。
  • 您是否尝试过在ModelState.Errors 集合中的一个ModelError 元素中获取ErrorMessage
  • 是的 - 我正在查看其中只有一件物品的收藏。
  • 好的,当您调试时,在您拥有的唯一项目中,当您查看属性ErrorMessage 时,那里的值是什么?
  • 我上面提到的 JSON 中未找到必需属性“myProperty”。路径'',第 23 行,位置 1。
猜你喜欢
  • 1970-01-01
  • 2016-01-27
  • 1970-01-01
  • 2022-01-08
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
相关资源
最近更新 更多