add kcp
This commit is contained in:
83
Src/Core/Models/ContextModel.cs
Normal file
83
Src/Core/Models/ContextModel.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
// ReSharper disable CheckNamespace
|
||||
namespace BITKit
|
||||
// ReSharper restore CheckNamespace
|
||||
{
|
||||
public record ContextModel
|
||||
{
|
||||
public static ContextModel Get(object data)
|
||||
{
|
||||
return new ContextModel()
|
||||
{
|
||||
StatusCode = 200,
|
||||
Message = "success",
|
||||
Data = data
|
||||
};
|
||||
}
|
||||
public static ContextModel Error(string message)
|
||||
{
|
||||
return new ContextModel()
|
||||
{
|
||||
StatusCode = 500,
|
||||
Message = message,
|
||||
Data = false
|
||||
};
|
||||
}
|
||||
public static ContextModel GetFromJson(string json)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = new ContextModel();
|
||||
var jObject = JObject.Parse(json);
|
||||
if(jObject.TryGetValue("status_code",out var statusCode))
|
||||
result.StatusCode = statusCode.Value<int>();
|
||||
if(jObject.TryGetValue("message",out var message))
|
||||
result.Message = message.Value<string>();
|
||||
if (jObject.TryGetValue("data", out var data))
|
||||
result.Data = data;
|
||||
return JsonConvert.DeserializeObject<ContextModel>(json);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
BIT4Log.Warning(json);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
public static implicit operator string(ContextModel self)
|
||||
{
|
||||
return self.ToString();
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return JsonConvert.SerializeObject(this);
|
||||
}
|
||||
|
||||
[JsonProperty("status_code")]
|
||||
public int StatusCode;
|
||||
[JsonProperty("message")]
|
||||
public string Message=string.Empty;
|
||||
[JsonProperty("data")]
|
||||
public object Data=string.Empty;
|
||||
[JsonIgnore]
|
||||
public bool IsSuccess => StatusCode is 200 or 0;
|
||||
public bool TryAs<T>(out T value)
|
||||
{
|
||||
switch (Data)
|
||||
{
|
||||
case T t:
|
||||
value = t;
|
||||
return true;
|
||||
case JToken jToken:
|
||||
value = jToken.ToObject<T>();
|
||||
return true;
|
||||
default:
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user