Asp.NetCore3.1 Model validation

1. ConfigureServices

services.AddControllersWithViews(config=>config.Filters.Add(typeof(ModelValidateActionFilterAttribute)));


2. ModelValidateActionFilterAttribute.cs

    public class ModelValidateActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                //公共返回数据类
                ReturnMsg returnMsg = new ReturnMsg() { Code = "-1" };

                //获取具体的错误消息
                foreach (var item in context.ModelState.Values)
                {
                    //遍历所有项目的中的所有错误信息
                    foreach (var err in item.Errors)
                    {
                        //消息拼接,用|隔开,前端根据容易解析
                        returnMsg.Msg += $"{err.ErrorMessage}|";
                    }
                }
                context.Result = new JsonResult(returnMsg);
            }

        }
        public class ReturnMsg
        {
            /// <summary>
            /// 返回的Code
            /// </summary>
            public string Code { get; set; }

            /// <summary>
            /// 消息
            /// </summary>
            public string Msg { get; set; }

            /// <summary>
            /// 返回的数据
            /// </summary>
            public string Data { get; set; }
        }

    }

public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "account");
}

 

 

Asp.NetCore3.1 Model validation

上一篇:Token 在 Ajax 请求头中,服务端过滤器跨域问题


下一篇:vue+webpack切换环境和打包之后服务器配置