简体   繁体   English

如何在 ASP.NET Core 5 Web API 中创建一致的 API 响应 class

[英]How to create consistent API response class in ASP.NET Core 5 Web API

How would I create a consistent generic API response class in ASP.NET Core 5 Web API.我将如何在 ASP.NET Core 5 Web API 中创建一致的通用 API 响应 class。

Basically I want to have a response from API just like基本上我想得到 API 的回复,就像

{
    Status Code : 200 or 404 
    Result Count : 1 (null or 0 in case of error or no data found)
    Response : [array of data (error message in case of error)]
}

I have created below sample class but it is useful only in case of success response.我在下面创建了示例 class,但它仅在成功响应的情况下才有用。 I am not able to use it in error scenario because the Data property is of IEnumerable<T> data type and I can not pass error message in string.我无法在错误情况下使用它,因为Data属性是IEnumerable<T>数据类型,我无法在字符串中传递错误消息。 Any help please?有什么帮助吗?

Thanks in advance.提前致谢。

public class Result<T> 
{
    public int StatusCode { get; set; }
    public int Count { get; set; }
    public IEnumerable<T> Data { get; set; }
}

//sample code in controller
public IActionResult<IEnumerable<User>> GetAll()
{
    var list = _userRepository.GetAll();
    var model = new Result<User>
    {
        StatusCode = 200,
        Count = list.Count,
        Data = list
    };

    return Ok(model);
}

for returning errors you have to do it like this要返回错误,您必须这样做

        var list = new List<string>()
        {
           "invalidata"
        };
        var model = new Result<string>
        {
            StatusCode = 400,
            Count = 0,
            Data = list
        };

        return BadRequest(model);

then you get response like this.然后你会得到这样的回应。

在此处输入图像描述

public class ApiResponse
    {
        public ApiResponse(int statusCode, string message = null)
        {
            StatusCode = statusCode;
            Message = message ?? GetDefaultMessageStatusCode(statusCode);
        }

        public int StatusCode { get; set; }
        public string Message { get; set; }

         private string GetDefaultMessageStatusCode(int statusCode)
        {
            return statusCode switch {
                400 => "A bad request, you have made",
                401 => "Authorized, you are not",
                403 => "Forbidden from doing this, you are",
                404 => "Resource found, it was not",
                500 => "Errors are the path to the dark side. Errors lead to anger.  Anger leads to hate.  Hate leads to career change",
                _ => null
            };
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM