NetCore 统一输出格式

配置 API:示例源码下载

builder.Services.AddControllers();

app.MapControllers();

 错误代码:

public enum ResponseCode
{
    [Description("操作失败")]
    BadRequest = 1001,

    [Description("操作成功")]
    OK = HttpStatusCode.OK,
    [Description("没有权限")]
    Unauthorized = HttpStatusCode.Unauthorized,
    [Description("未找到服务")]
    NotFound = HttpStatusCode.NotFound,
    [Description("服务器理解请求客户端的请求,但是拒绝执行此请求")]
    Forbidden = HttpStatusCode.Forbidden,
    [Description("服务器内部错误,无法完成请求")]
    InternalServerError = HttpStatusCode.InternalServerError,
    [Description("请求错误")]
    BadGateway = HttpStatusCode.BadGateway
}

 

 统一输出格式:

public class BaseResponse
{
    /// <summary>
    /// 返回码
    /// </summary>
    public ResponseCode ErrorCode { set; get; }

    /// <summary>
    /// 是否成功
    /// </summary>
    public bool IsSuccess { get; set; } = true;

    /// <summary>
    /// 返回消息
    /// </summary>
    public string Message { get; set; } = "";
    public object Data { get; internal set; }

    /// <summary>
    /// 操作成功
    /// </summary>
    public static BaseResponse Success(string message = "操作成功")
    {
        return new BaseResponse { Message = "操作成功!", ErrorCode = ResponseCode.OK };
    }

    /// <summary>
    /// 操作失败
    /// </summary>
    public static BaseResponse Fail(string message = "操作失败!")
    {
        return new BaseResponse { Message = message, ErrorCode = ResponseCode.BadRequest };
    }

    /// <summary>
    /// 操作失败
    /// </summary>
    public static BaseResponse Fail(string message, ResponseCode code = ResponseCode.BadRequest)
    {
        return new BaseResponse { Message = message, ErrorCode = code };
    }

    /// <summary>
    /// 错误异常
    /// </summary>
    public static BaseResponse Error(string message = "错误异常")
    {
        return new BaseResponse { Message = message, ErrorCode = ResponseCode.InternalServerError };
    }

    /// <summary>
    /// 错误异常
    /// </summary>
    public static BaseResponse Error(string message, ResponseCode ErrorCode = ResponseCode.InternalServerError)
    {
        return new BaseResponse { Message = message, ErrorCode = ErrorCode };
    }
}

public class BaseResponse<T> : BaseResponse where T : class
{
    /// <summary>
    /// 返回实体
    /// </summary>
    public T Data { get; set; }

    /// <summary>
    /// 操作成功
    /// </summary>
    public static BaseResponse Success(T data, string message = "操作成功")
    {

        return new BaseResponse { Message = "操作成功!", Data = data, ErrorCode = ResponseCode.OK };
    }
}

public class PageResponse<T> : BaseResponse where T : class
{
    /// <summary>
    /// 总记录条数
    /// </summary>
    public int Total { get; set; }

    /// <summary>
    /// 响应数据
    /// </summary>
    public List<T> Data { get; set; }
}
posted @ 2024-01-04 16:08  microsoft-zhcn  阅读(23)  评论(0编辑  收藏  举报