46 lines
1.5 KiB
C#
46 lines
1.5 KiB
C#
|
|
using Microsoft.AspNetCore.Mvc;
|
|||
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
|||
|
|
using QYZH.InteractiveMagazine.Models.Dto;
|
|||
|
|
|
|||
|
|
|
|||
|
|
namespace QYZH.InteractiveMagazine.Infrastructure.Middleware;
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 数据验证过滤器
|
|||
|
|
/// </summary>
|
|||
|
|
public class ModelValidActionFilterAttribute : ActionFilterAttribute
|
|||
|
|
{
|
|||
|
|
public override void OnActionExecuting(ActionExecutingContext context)
|
|||
|
|
{
|
|||
|
|
if (!context.ModelState.IsValid)
|
|||
|
|
{
|
|||
|
|
Dictionary<string, string> errorDic = new Dictionary<string, string>();
|
|||
|
|
foreach (var key in context.ModelState.Keys)
|
|||
|
|
{
|
|||
|
|
var modelstate = context.ModelState[key];
|
|||
|
|
if (modelstate.Errors.Any())
|
|||
|
|
{
|
|||
|
|
string errorStr = string.Join(",", modelstate.Errors.Select(e => e.ErrorMessage).ToList());
|
|||
|
|
errorDic.Add(key, errorStr);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
var result = new BaseResponse<Dictionary<string, string>>() { Code = ResultCode.FAIL };
|
|||
|
|
|
|||
|
|
result.Message = string.Join("|", errorDic.Select(e => e.Value).Distinct());
|
|||
|
|
result.Result = errorDic;
|
|||
|
|
context.Result = new JsonResult(result);
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
//public override void OnActionExecuted(ActionExecutedContext context)
|
|||
|
|
//{
|
|||
|
|
// if (context.Exception != null)
|
|||
|
|
// {
|
|||
|
|
// BaseResponse result = new BaseResponse() { Code = ResultCode.Fail };
|
|||
|
|
// result.Message = context.Exception.Message;
|
|||
|
|
// context.Result = new JsonResult(result);
|
|||
|
|
// }
|
|||
|
|
//}
|
|||
|
|
}
|
|||
|
|
|