using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace YYApi.Communications
{
public class BaseResponse
{
///
/// 错误代码
///
public int Code { get; set; }
///
/// 错误描述
///
public string Message { get; set; }
///
/// 默认错误代码对应提示信息
///
private readonly Dictionary MsgBox = new Dictionary()
{
{200, "成功"},
{400, "参数错误"},
{401, "需要登录"},
{403, "无权访问"},
{404, "接口不存在"},
{500, "服务器错误"}
};
///
/// 返回一个成功的空结果
///
public BaseResponse()
{
SetCode(200);
}
///
/// 返回指定代码的描述
///
/// 错误代码
public BaseResponse(int code)
{
SetCode(code);
}
///
/// 返回指定代码的结果,并自定义提示信息
///
/// 错误代码
/// 错误信息
public BaseResponse(int code, string message)
{
SetCodeMsg(code, message);
}
///
/// 设置响应结果的错误代码
///
/// 错误代码
public void SetCode(int code)
{
Code = code;
Message = MsgBox.ContainsKey(code) ? MsgBox[code] : "未知错误";
}
///
/// 设置响应结果的错误代码和错误描述
///
/// 错误代码
/// 错误描述
public void SetCodeMsg(int code, string message)
{
SetCode(code);
if (!string.IsNullOrEmpty(message))
{
Message = message;
}
}
///
/// 序列化为JSON字符串
///
///
public override string ToString()
{
return JsonSerializer.Serialize(this, new JsonSerializerOptions
{
IgnoreReadOnlyProperties = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() }
});
}
}
}