【问题标题】:When checking whether a ModelState is valid, is there a way to return the specific error?在检查 ModelState 是否有效时,有没有办法返回特定的错误?
【发布时间】:2019-11-25 22:03:19
【问题描述】:

在检查一个ModelState是否有效时,有没有办法返回具体的错误?

假设我正在使用以下代码检查我的控制器中是否有任何错误。

控制器

if (!ModelState.IsValid)
                return BadRequest( "Invalid request");

我的模特:

[StringLength(500, ErrorMessage = "cant have more than 500 caracteres")]
public string Description { get; set; }

我希望它返回模型错误“不能超过 500 个字符”,我该如何处理?

【问题讨论】:

标签: asp.net asp.net-mvc model-view-controller


【解决方案1】:

是的,您可以,请参阅ModelState 属性。

例子:

if (!ModelState.IsValid)
{
    var message = string.Join(" | ", ModelState.Values
        .SelectMany(v => v.Errors)
        .Select(e => e.ErrorMessage));
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, message);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-07
    • 2020-09-18
    • 2018-10-10
    • 2011-01-30
    • 2011-06-03
    • 2022-10-04
    • 2021-01-02
    • 1970-01-01
    相关资源
    最近更新 更多