1、创建模型:
/// <summary>
/// 统一返回模型
/// </summary>
public class ApiResult
{
/// <summary>
/// 是否成功
/// </summary>
public bool isSuccess { get; set; }
/// <summary>
/// 状态码
/// </summary>
public int code { get; set; }
/// <summary>
/// 返回数据集合
/// </summary>
public object data { get; set; }
/// <summary>
/// 显示信息
/// </summary>
public string msg { get; set; }
/// <summary>
/// 开发者返回信息
/// </summary>
public string msgDev { get; set; }
}
2、封装简单操作
/// <summary>
/// 统一返回模型 帮助类
/// </summary>
public class ApiResultHelper
{
/// <summary>
/// 常用成功
/// </summary>
/// <param name="res">数据集合</param>
/// <returns></returns>
public static ApiResult Success(object res)
{
return new ApiResult() { isSuccess = true, code = 200, data = res };
}
/// <summary>
/// 常用错误
/// </summary>
/// <param name="message">用户提示</param>
/// <param name="devmsg">开发者提示</param>
/// <returns></returns>
public static ApiResult Error(string message, string devmsg = "")
{
return new ApiResult() { isSuccess = false, code = 400, msg = message, msgDev = devmsg };
}
/// <summary>
/// 自定义(等价于new ApiResult了)
/// </summary>
/// <param name="isSuccess"></param>
/// <param name="code"></param>
/// <param name="message"></param>
/// <param name="devmsg"></param>
/// <param name="data"></param>
/// <returns></returns>
public static ApiResult Custom(bool isSuccess, int code, string message, string devmsg, object data)
{
return new ApiResult() { isSuccess = false, code = 400, msg = message, msgDev = devmsg, data = data };
}
}
3、测试代码
/// <summary>
/// 测试连接1
/// 异常
/// </summary>
/// <param name="t">字符串</param>
/// <returns></returns>
[HttpGet]
[ApiVersionCustomRoute(SwaggerDocSettings.ApiVersions.v1)]
public ApiResult Test(string t)
{
int i = 0;
try
{
i = int.Parse(t);
}
catch (Exception ex)
{
return ApiResultHelper.Error("转化失败", ex.Message.ToString());
}
return ApiResultHelper.Success("转化成功!");
}
4、结果:
4.1、失败:
4.2、成功: