首页 > 其他分享 >分享一下.net core mvc的ModelStateExtend

分享一下.net core mvc的ModelStateExtend

时间:2022-11-14 16:15:26浏览次数:57  
标签:core Errors Key item mvc ModelStateExtend var new public

主要代码:

using Cracker.Core.Function;

using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Cracker.Core.Utils.Extend
{
    public static class ModelStateExtend
    {
        public static IEnumerable<ShowError> AllModelStateErrors(this ModelStateDictionary modelState)
        {
            var result = new List<ShowError>();
            //找到出错的字段以及出错信息
            var errorFieldsAndMsgs = modelState.Where(m => m.Value.Errors.Any())
                .Select(x => new { x.Key, x.Value.Errors });
            foreach (var item in errorFieldsAndMsgs)
            {
                //获取键
                var fieldKey = item.Key;
                //获取键对应的错误信息
                var fieldErrors = item.Errors
                    .Select(e => new ShowError(fieldKey, e.ErrorMessage));
                result.AddRange(fieldErrors);
            }
            return result;
        }

        /// <summary>
        /// 验证入参
        /// </summary>
        /// <param name="modelState"></param>
        /// <exception cref="Fail"></exception>
        public static void ValidateInComeParams(ModelStateDictionary modelState)
        {
            var errorFieldsAndMsgs = modelState.Where(m => m.Value.Errors.Any())
                .Select(x => new { x.Key, x.Value.Errors });
            foreach (var item in errorFieldsAndMsgs)
            {
                var error = item.Errors.Single();
                if (error is not null)
                {
                    throw new Fail(error.ErrorMessage);
                }
            }
        }
    }
}

ShowError.cs:

namespace Cracker.Core.Function
{
    public class ShowError
    {
        public ShowError(string key, string message)
        {
            Key = key;
            Message = message;
        }

        public string Key { get; set; }
        public string Message { get; set; }
    }
}

标签:core,Errors,Key,item,mvc,ModelStateExtend,var,new,public
From: https://www.cnblogs.com/crackerwork/p/16889324.html

相关文章