ASP.NET Core 一个Json返回类

很多时候(如Ajax)我们需要从Web应用中得到标准的反馈以便进行数据分析。

为此,我将各类返回标准化封装,客户端将统一得到 JSON:[{"status":200,"message":"success","data":[Object]}],有利于建立统一的数据处理模型。

    public class ReturnStd
    {
        public class ReturnJson
        {
            public string Status { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }
        public static ReturnJson ComJson(string responseMessage, string responseCode, object rtnData = null)
        {
            ReturnJson returnJson = new ReturnJson()
            {
                Status = responseCode,
                Message = responseMessage,
                Data = rtnData ?? string.Empty
            };
            return returnJson;
        }

        public static ReturnJson Success(object rtnData = null)
        {
            ReturnJson returnJson = new ReturnJson()
            {
                Status = "200",
                Message = string.Empty,
                Data = rtnData?? string.Empty
            };
            return returnJson;
        }

        public static ReturnJson Error(string responseMessage, string responseCode = "400", object rtnData = null)
        {
            ReturnJson returnJson = new ReturnJson()
            {
                Status = responseCode,
                Message = responseMessage ?? string.Empty,
                Data = rtnData ?? string.Empty
            };
            return returnJson;
        }

        public static ReturnJson ModelError(ModelStateDictionary modelState, string responseCode = "400", object rtnData = null)
        {
            string messages = string.Join("; ", modelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));

            ReturnJson returnJson = new ReturnJson()
            {
                Status = responseCode,
                Message = messages,
                Data = rtnData ?? string.Empty
            };
            return returnJson;
        }

        public static ReturnJson NotAuthorize(string responseMessage, string responseCode = "90", object rtnData = null)
        {
            ReturnJson returnJson = new ReturnJson()
            {
                Status = responseCode,
                Message = responseMessage ?? string.Empty,
                Data = rtnData ?? string.Empty
            };
            return returnJson;
        }

    }

  如何使用?

        [HttpGet]
        public JsonResult GetUsers(long lastUpdateTicks=0)
        {
            List<SYS_User_OnCloud> rtnData = _context.SYS_User_OnClouds.Where(u => ((long?)u.LastUpdateTicks?? 0) >= lastUpdateTicks).ToList();
            return Json(ReturnStd.Success(rtnData));
        }

  

posted @ 2018-10-16 22:42  ROTA  阅读(4514)  评论(2编辑  收藏  举报