using System; using System.Collections.Generic; using System.ComponentModel; using Hncore.Infrastructure.Common; using Hncore.Infrastructure.Extension; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; namespace Hncore.Infrastructure.OpenApi { public class OpenApiResult where T : class, new() { [JsonProperty("code")] public OpenApiReturnCode Code { get; private set; } [JsonProperty("message")] public string Message { get; private set; } = ""; [JsonProperty("timestamp")] public long Timestamp { get; set; } [JsonProperty("sign")] public string Sign { get; set; } [JsonProperty("data")] public T Data { get; set; } = new T(); private static readonly Dictionary Dic; static OpenApiResult() { Dic = ObjectExtension.ToDescriptionDictionary(); } public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") { Code = code; if (string.IsNullOrEmpty(message) && Dic.ContainsKey(Code)) { Message = Dic[Code]; } else { Message = message; } this.Timestamp = DateTimeHelper.ToUnixTimestamp(DateTime.Now); } public void CreateSign(string key) { this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); } public OpenApiResult CreateSign(HttpContext httpContext) { var key = httpContext.Items["OpenApiAppKey"].ToString(); this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); return this; } } public class OpenApiResult : OpenApiResult { public OpenApiResult(OpenApiReturnCode code = OpenApiReturnCode.Success, string message = "") : base(code, message) { } public new OpenApiResult CreateSign(HttpContext httpContext) { var key = httpContext.Items["OpenApiAppKey"].ToString(); this.Sign = OpenApiSignUtil.CreateSign(this.Timestamp, key); return this; } } public enum OpenApiReturnCode { /// /// 成功 /// [Description("成功")] Success = 10000, /// /// 验签失败 /// [Description("未授权")] Unauthorized = 40001, /// /// 验签失败 /// [Description("验签失败")] SignError = 40002, /// /// 时间戳过期 /// [Description("时间戳过期")] TimeStampExpired = 40003, /// /// 内部错误 /// [Description("内部错误")] InternalError = 50000, /// /// 处理失败 /// [Description("处理失败")] Error = 500001 } }