ApiResult-WebAPI开发统一返回值对象的演化(.net core版)

 

API_Result是本人对WebAPI方法返回值的命名,这是个人行为。 这样定义已经好多年了,是时候重构了,这应该是很认真写的一个类了吧。看笑话的请进。重构心得:加入链式调用方法和使用泛型来简化代码。

这是第一版

    /// <summary>
    /// API返回值数据传输对象
    /// </summary>
    public class ApiResult
    {
        public string Code { get; set; } = "-1";
        /// <summary>
        /// API调用是否成功
        /// </summary>
        public bool Success { get; set; } = false;
        /// <summary>
        /// 服务器回应消息提示
        /// </summary>
        public string ResultMessage { get; set; }
        /// <summary>
        /// 服务器回应的返回值对象(API调用失败则返回异常对象)
        /// </summary>
        public object ResultObject { get; set; }
        /// <summary>
        /// 服务器回应时间
        /// </summary>
        public string ResponseDatetime { get; set; }
}

这是改进版

    /// <summary>
    /// API返回值数据传输对象
    /// </summary>
    public class ApiResult
    {
        public string Code { get; set; } = "-1";
        /// <summary>
        /// API调用是否成功
        /// </summary>
        public bool Success { get; set; } = false;
        /// <summary>
        /// 服务器回应消息提示
        /// </summary>
        public string ResultMessage { get; set; }
        /// <summary>
        /// 服务器回应的返回值对象(API调用失败则返回异常对象)
        /// </summary>
        public object ResultObject { get; set; }
        /// <summary>
        /// 服务器回应时间
        /// </summary>
        public string ResponseDatetime { get; set; }

        /// <summary>
        /// 设置API调用结果为成功
        /// </summary>
        /// <returns></returns>
        public ApiResult SetSuccessResult()
        {
            Code = "0";
            ResponseDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
            Success = true;
            ResultMessage = "Success";
            ResultObject = string.Empty;
            return this;
        }
        /// <summary>
        /// 设置API调用结果为成功
        /// </summary>
        /// <param name="resultObject">不需要从Data里面读取返回值对象时,存储简单的值对象或者string</param>
        /// <returns></returns>
        public ApiResult SetSuccessResult(string resultObject)
        {
            Code = "0";
            ResponseDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
            Success = true;
            ResultMessage = "Success";
            ResultObject = resultObject;
            return this;
        }
        /// <summary>
        /// 设置API调用结果为失败
        /// </summary>
        /// <param name="errorCode">错误代码</param>
        /// <param name="errorMessage">错误消息</param>
        /// <returns></returns>
        public ApiResult SetFailedResult(string errorCode, string errorMessage)
        {
            Code = errorCode;
            ResponseDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
            Success = false;
            ResultMessage = errorMessage;
            ResultObject = string.Empty;
            return this;
        }
        /// <summary>
        /// 设置API调用结果为失败
        /// </summary>
        /// <param name="errorCode">错误代码</param>
        /// <param name="errorMessage">错误消息</param>
        /// <param name="e">异常对象</param>
        /// <returns></returns>
        public ApiResult SetFailedResult(string errorCode, string errorMessage, Exception e)
        {
            Code = errorCode;
            ResponseDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff");
            Success = false;
            ResultMessage = errorMessage;
            ResultObject = e;
            return this;
        }
    }
    /// <summary>
    /// API返回值数据传输对象(泛型版)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ApiResult<T> : ApiResult
    {
        public virtual T Data { get; set; }

        public virtual ApiResult<T> SetSuccessResult(T t)
        {
            var result = new ApiResult<T>();            
            result.SetSuccessResult().ResultObject = t.GetType().Name;
            result.Data = t;
            return result;
        }
    }

 

使用

        /// <summary>
        /// 客户端测试控制器的可用性,服务器返回欢迎词
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("welcome")]
        public ContentResult Welcome()
        {
            return new ContentResult
            {
                StatusCode = 200,
                ContentType = "text/html",
                Content = JsonConvert.SerializeObject(new ApiResult().SetSuccessResult("Welcome!"))
            };
        }

                     /// <summary>
                    /// 查看全局配置项
                    /// </summary>
                    /// <returns></returns>
                    [HttpPost]
                    public ApiResult<IOptions<AppSettings>> ShowConfig()
                     {
                           return new ApiResult<IOptions<AppSettings>>().SetSuccessResult(_settings);
                    }

小插曲

  •  在Debug模式和生产环境使用postman调用api,发现调用api的耗时有几百倍的差距,还以为代码写得有问题呢。
  • .net core 3.1默认不是使用Newtonsoft.Json来序列号json对象的,设置json对象属性首字母不小写需要使用下面的代码:

 

  services.AddControllers().AddJsonOptions(options =>
            {
                //格式化日期时间格式
                options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
                //数据格式原样输出
                options.JsonSerializerOptions.PropertyNamingPolicy = null;
                //取消Unicode编码
                options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
                //忽略空值
                options.JsonSerializerOptions.IgnoreNullValues = true;
                //允许额外符号
                options.JsonSerializerOptions.AllowTrailingCommas = true;
                //反序列化过程中属性名称是否使用不区分大小写的比较
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
            }); 



    public class DatetimeJsonConverter: JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                if (DateTime.TryParse(reader.GetString(), out DateTime date))
                    return date;
            }
            return reader.GetDateTime();
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }

 

posted @ 2020-03-25 11:03  数据酷软件  阅读(3516)  评论(1编辑  收藏  举报