using System.Text;
using System.Web.Http.ModelBinding;
public static class MyExtensionMethods
{
public static string GetAllErrorMessages(this ModelStateDictionary modelState, string separator = " ")
{
if (separator == null)
{
separator = " ";
}
StringBuilder sbErrors = new StringBuilder();
foreach (ModelState modelStateValues in modelState.Values)
{
foreach (ModelError error in modelStateValues.Errors)
{
if (string.IsNullOrWhiteSpace(error.ErrorMessage))
{
if (error.Exception != null)
{
sbErrors.Append(error.Exception.Message);
sbErrors.Append(separator);
}
}
else
{
sbErrors.Append(error.ErrorMessage);
sbErrors.Append(separator);
}
}
}
if (sbErrors.Length > separator.Length)
{
sbErrors.Remove(sbErrors.Length - separator.Length, separator.Length);
}
string errorMessage = sbErrors.ToString();
if (string.IsNullOrWhiteSpace(errorMessage))
{
errorMessage = string.Empty;
}
return errorMessage;
}
}
using System.Web.Http;
public class ExampleController : ApiController
{
[HttpPost]
public IHttpActionResult Usage([FromBody]YourClass body)
{
if (!this.ModelState.IsValid)
{
return this.BadRequest(this.ModelState.GetAllErrorMessages());
}
}
}
I use this code to get all MVC validations errors and so return this as the message of Bad Request.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.