ASP.NET MVC How to convert ModelState errors to json

前端 未结 13 2125
余生分开走
余生分开走 2020-12-04 05:24

How do you get a list of all ModelState error messages? I found this code to get all the keys: ( Returning a list of keys with ModelState errors)

var errorK         


        
13条回答
  •  情书的邮戳
    2020-12-04 05:52

    Take a look at System.Web.Http.Results.OkNegotiatedContentResult.

    It converts whatever you throw into it to JSON.

    So I did this

    var errorList = ModelState.ToDictionary(kvp => kvp.Key.Replace("model.", ""), kvp => kvp.Value.Errors[0].ErrorMessage);
    
    return Ok(errorList);
    

    This resulted in:

    {
      "Email":"The Email field is not a valid e-mail address."
    }
    

    I am yet to check what happens when there is more than one error for each field but the point is the OkNegoriatedContentResult is brilliant!

    Got the linq/lambda idea from @SLaks

提交回复
热议问题