DocSpace-client/common/ASC.Api.Core/Middleware/CommonApiResponse.cs

99 lines
2.6 KiB
C#
Raw Normal View History

2019-05-30 09:28:21 +00:00
using System;
2019-06-13 12:12:21 +00:00
using System.Collections.Generic;
2019-08-15 12:04:42 +00:00
using System.Linq;
2019-05-30 09:28:21 +00:00
using System.Net;
namespace ASC.Api.Core.Middleware
{
2019-05-30 14:57:15 +00:00
public abstract class CommonApiResponse
2019-05-30 09:28:21 +00:00
{
public int Status { get; set; }
public HttpStatusCode StatusCode { get; set; }
2019-05-30 14:57:15 +00:00
protected CommonApiResponse(HttpStatusCode statusCode)
{
StatusCode = statusCode;
}
}
2019-05-30 09:28:21 +00:00
2019-05-30 14:57:15 +00:00
public class ErrorApiResponse : CommonApiResponse
{
public CommonApiError Error { get; set; }
2021-12-13 16:23:05 +00:00
protected internal ErrorApiResponse(HttpStatusCode statusCode, Exception error, string message, bool withStackTrace) : base(statusCode)
2019-05-30 09:28:21 +00:00
{
2019-05-30 14:57:15 +00:00
Status = 1;
2021-12-13 16:23:05 +00:00
Error = CommonApiError.FromException(error, message, withStackTrace);
2019-05-30 09:28:21 +00:00
}
2019-05-30 14:57:15 +00:00
}
2019-05-30 09:28:21 +00:00
2019-05-30 14:57:15 +00:00
public class SuccessApiResponse : CommonApiResponse
{
public int? Count { get; set; }
2019-07-29 10:51:14 +00:00
public long? Total { get; set; }
2019-05-30 14:57:15 +00:00
public object Response { get; set; }
protected internal SuccessApiResponse(HttpStatusCode statusCode, object response, long? total = null, int? count = null) : base(statusCode)
2019-05-30 09:28:21 +00:00
{
2019-05-30 14:57:15 +00:00
Status = 0;
Response = response;
2019-07-29 10:51:14 +00:00
Total = total;
2019-06-13 12:12:21 +00:00
if (count.HasValue)
2019-08-30 12:40:57 +00:00
{
Count = count;
2019-06-13 12:12:21 +00:00
}
else
{
if (response is List<object> list)
{
Count = list.Count;
}
else if (response is IEnumerable<object> collection)
{
Count = collection.Count();
}
else if (response == null)
{
Count = 0;
}
else
{
Count = 1;
}
2019-06-13 12:12:21 +00:00
}
2019-05-30 09:28:21 +00:00
}
}
public class CommonApiError
{
public string Message { get; set; }
public string Type { get; set; }
2019-05-30 09:28:21 +00:00
public string Stack { get; set; }
public int Hresult { get; set; }
2021-12-13 16:23:05 +00:00
public static CommonApiError FromException(Exception exception, string message, bool withStackTrace)
2019-05-30 09:28:21 +00:00
{
2021-12-13 16:23:05 +00:00
var result = new CommonApiError()
2019-05-30 09:28:21 +00:00
{
2021-12-13 16:23:05 +00:00
Message = message ?? exception.Message
2019-05-30 09:28:21 +00:00
};
2021-12-13 16:23:05 +00:00
if (withStackTrace)
{
result.Type = exception.GetType().ToString();
result.Stack = exception.StackTrace;
result.Hresult = exception.HResult;
}
return result;
2019-05-30 09:28:21 +00:00
}
}
}