.net core restful api 返回数据格式

 /// <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!"))
    };
}
 
.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-08-31 14:32  恋之呓  阅读(1154)  评论(0编辑  收藏  举报