You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/Infrastructure/Extensions/ModelStateDictionaryExtensi...

61 lines
2.0 KiB

using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
namespace Infrastructure.Extensions
{
public static class ModelStateDictionaryExtensions
{
public static void AddModelError(this ModelStateDictionary modelState, IList<ValidationResult> validationResults)
{
if (modelState is null)
{
throw new ArgumentNullException(nameof(modelState));
}
if (validationResults is null)
{
throw new ArgumentNullException(nameof(validationResults));
}
foreach (var item in validationResults)
{
if (item.MemberNames.Any())
{
foreach (var key in item.MemberNames)
{
modelState.AddModelError(key, item.ErrorMessage);
}
}
else
{
modelState.AddModelError("", item.ErrorMessage);
}
}
}
public static object AddModelError(this ModelStateDictionary modelState, string message, string key = "", int code = 0)
{
if (modelState is null)
{
throw new ArgumentNullException(nameof(modelState));
}
modelState.AddModelError(key, message);
return new
{
code,
key = string.IsNullOrEmpty(key) ? key : key.Substring(0, 1).ToLower(CultureInfo.InvariantCulture) + key.Substring(1),
message
};
}
public static object AddModelError(this ModelStateDictionary modelState, Expression<Func<object, object>> expression, string message, int code = 0)
{
return modelState.AddModelError(message, expression.GetPropertyName(), code);
}
}
}