【问题标题】:.Net Webapi doesen't show errormessage of required properties.Net Web Api 不显示所需属性的错误消息
【发布时间】: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


【解决方案1】:

尝试使用这个:

public IHttpActionResult PostData(DataModel data)
    {
        if (ModelState.IsValid)
        {
            // This part is working fine..
            return Ok(ProcessData(data));
        }
        else
        {
            // errs do only contain Exception.Messages not ErrorMessages..
            string errs = ModelState.Select(x => x.Value.Errors)
                       .Where(y=>y.Count>0)
                       .ToList();
            return Ok(errs);
        }
    }

如果请求的模型data 是有效的,它将返回您的模型的响应 如果模型无效,将返回 list of string 和错误消息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多