首页 > Web开发 > 详细

Asp.NetCore3.1 Model validation

时间:2020-06-18 17:03:43      阅读:111      评论:0      收藏:0      [点我收藏+]
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

原文:https://www.cnblogs.com/LiuFengH/p/13158083.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!