API_Result是本人對WebAPI方法返回值的命名,這是個人行為。 這樣定義已經好多年了,是時候重構了,這應該是很認真寫的一個類了吧。看笑話的請進。重構心得:加入鏈式調用方法和使用泛型來簡化代碼。
這是第一版
/// <summary>
/// API返回值數據傳輸對象 /// </summary>
public class ApiResult { public string Code { get; set; } = "-1"; /// <summary>
/// API調用是否成功 /// </summary>
public bool Success { get; set; } = false; /// <summary>
/// 服務器回應消息提示 /// </summary>
public string ResultMessage { get; set; } /// <summary>
/// 服務器回應的返回值對象(API調用失敗則返回異常對象) /// </summary>
public object ResultObject { get; set; } /// <summary>
/// 服務器回應時間 /// </summary>
public string ResponseDatetime { get; set; } }
這是改進版
/// <summary>
/// API返回值數據傳輸對象 /// </summary>
public class ApiResult { public string Code { get; set; } = "-1"; /// <summary>
/// API調用是否成功 /// </summary>
public bool Success { get; set; } = false; /// <summary>
/// 服務器回應消息提示 /// </summary>
public string ResultMessage { get; set; } /// <summary>
/// 服務器回應的返回值對象(API調用失敗則返回異常對象) /// </summary>
public object ResultObject { get; set; } /// <summary>
/// 服務器回應時間 /// </summary>
public string ResponseDatetime { get; set; } /// <summary>
/// 設置API調用結果為成功 /// </summary>
/// <returns></returns>
public ApiResult SetSuccessResult() { Code = "0"; ResponseDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); Success = true; ResultMessage = "Success"; ResultObject = string.Empty; return this; } /// <summary>
/// 設置API調用結果為成功 /// </summary>
/// <param name="resultObject">不需要從Data里面讀取返回值對象時,存儲簡單的值對象或者string</param>
/// <returns></returns>
public ApiResult SetSuccessResult(string resultObject) { Code = "0"; ResponseDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); Success = true; ResultMessage = "Success"; ResultObject = resultObject; return this; } /// <summary>
/// 設置API調用結果為失敗 /// </summary>
/// <param name="errorCode">錯誤代碼</param>
/// <param name="errorMessage">錯誤消息</param>
/// <returns></returns>
public ApiResult SetFailedResult(string errorCode, string errorMessage) { Code = errorCode; ResponseDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); Success = false; ResultMessage = errorMessage; ResultObject = string.Empty; return this; } /// <summary>
/// 設置API調用結果為失敗 /// </summary>
/// <param name="errorCode">錯誤代碼</param>
/// <param name="errorMessage">錯誤消息</param>
/// <param name="e">異常對象</param>
/// <returns></returns>
public ApiResult SetFailedResult(string errorCode, string errorMessage, Exception e) { Code = errorCode; ResponseDatetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"); Success = false; ResultMessage = errorMessage; ResultObject = e; return this; } } /// <summary>
/// API返回值數據傳輸對象(泛型版) /// </summary>
/// <typeparam name="T"></typeparam>
public class ApiResult<T> : ApiResult { public virtual T Data { get; set; } public virtual ApiResult<T> SetSuccessResult(T t) { var result = new ApiResult<T>(); result.SetSuccessResult().ResultObject = t.GetType().Name; result.Data = t; return result; } }
使用
/// <summary>
/// 客戶端測試控制器的可用性,服務器返回歡迎詞
/// </summary>
/// <returns></returns>
[HttpGet, Route("welcome")]
public ContentResult Welcome()
{
return new ContentResult
{
StatusCode = 200,
ContentType = "text/html",
Content = JsonConvert.SerializeObject(new ApiResult().SetSuccessResult("Welcome!"))
};
}
/// <summary>
/// 查看全局配置項
/// </summary>
/// <returns></returns>
[HttpPost]
public ApiResult<IOptions<AppSettings>> ShowConfig()
{
return new ApiResult<IOptions<AppSettings>>().SetSuccessResult(_settings);
}

小插曲
- 在Debug模式和生產環境使用postman調用api,發現調用api的耗時有幾百倍的差距,還以為代碼寫得有問題呢。
- .net core 3.1默認不是使用Newtonsoft.Json來序列號json對象的,設置json對象屬性首字母不小寫需要使用下面的代碼:
services.AddControllers().AddJsonOptions(options => { //格式化日期時間格式
options.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter()); //數據格式原樣輸出
options.JsonSerializerOptions.PropertyNamingPolicy = null; //取消Unicode編碼
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); //忽略空值
options.JsonSerializerOptions.IgnoreNullValues = true; //允許額外符號
options.JsonSerializerOptions.AllowTrailingCommas = true; //反序列化過程中屬性名稱是否使用不區分大小寫的比較
options.JsonSerializerOptions.PropertyNameCaseInsensitive = false; }); public class DatetimeJsonConverter: JsonConverter<DateTime> { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { if (DateTime.TryParse(reader.GetString(), out DateTime date)) return date; } return reader.GetDateTime(); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss")); } }
