1.创建返回对象
/// <summary>
/// 回执对象
/// </summary>
public class ResultMsg
{
public int ResultCode { get; set; }//状态码
public string ResultMessage { get; set; }//提示消息
public object data { get; set; }//返回数据
public ResultMsg SetResultMsg(int code, string msg, object datas)
{
ResultCode = code;
ResultMessage = msg;
data = datas;
return this;
}
}
2.创建状态码枚举
/// <summary>
/// 状态码
/// </summary>
public enum ResultCode
{
[Description("成功")]
SUCCESS = 200,
[Description("失败")]
FAIL = 400,
[Description("请求不合理,服务器拒绝执行")]
UNAUTHORIZED = 403,
[Description("找不到所需数据")]
NOT_FOUND = 404,
[Description("服务器内部错误")]
INTERNAL_SERVER_ERROR = 500
}
3.创建获取枚举Descripion的方法
/// <summary>
/// 获取枚举的描述信息
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string GetDescription(this object value)
{
if (value == null)
return string.Empty;
Type type = value.GetType();
var fieldInfo = type.GetField(Enum.GetName(type, value));
if (fieldInfo != null)
{
if (Attribute.IsDefined(fieldInfo, typeof(DescriptionAttribute)))
{
var description =
Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (description != null)
return description.Description;
}
}
return string.Empty;
}
4.使用方法
public ResultMsg Fun()
{
ResultMsg resultMsg = new ResultMsg();
resultMsg = resultMsg.SetResultMsg(
(int)ResultCode.SUCCESS,//状态码200
Fun_Helper.GetDescription(ResultCode.SUCCESS), //状态码消息“成功”
data);//你要返回的数据object
return resultMsg;
}