在一個后端接口系統中,發布的接口,數據交互應該有一套統一的標准,以便調用方有一個高效、統一的處理。
而每個業務程序開發人員,可能只關心自己相對應的接口業務,而造成數據格式不同和大量的相應的日志記錄操作。
所以需要一套統一的日志記錄和簡單統一的數據結構封裝
1、在WebApi項目中添加自定義消息處理委托類:CustomMessageDelegatingHandler
/// <summary> /// API自定義消息處理委托類。 /// 對消息進行自定義操作、日志記錄。 /// </summary> public class CustomMessageDelegatingHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { //請求參數記錄 string guid = Guid.NewGuid().ToString("N"); LogHelper.WriteLog(guid + "-[" + request.Method.Method + "]:" + request.RequestUri); return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { HttpResponseMessage response = responseToCompleteTask.Result; HttpError error = null; if (response.TryGetContentValue<HttpError>(out error)) { //添加自定義錯誤處理 //error.Message = "Your Customized Error Message"; } if (error != null) { //封裝處理異常信息,返回指定JSON對象 WebAPIResultEntity webAPIResult = new WebAPIResultEntity() { status_code = "-999", message = error.Message + error.ExceptionMessage }; //response.Content = new StringContent(ConversionHelper.ObjectToJson(webAPIResult), System.Text.Encoding.UTF8, "application/json"); } else { //可以將反饋的數據讀取出來重新封裝按照指定格式統一返回 var str = response.Content.ReadAsStringAsync().Result; //數據封裝... //response.Content = new StringContent(str, System.Text.Encoding.UTF8, "application/json"); } //反饋參數記錄 LogHelper.WriteLog(guid + "-" + response.Content.ReadAsStringAsync().Result); return response; }); } }
2、在WebApiConfig中添加注冊消息類
//自定義消息類型
config.MessageHandlers.Add(new CustomMessageDelegatingHandler());
這樣調用接口時,就可以統一記錄請求參數和反饋數據、也能統一封裝自己想要的數據包裝格式
如:
{
"data":{
"result":"123"
},
"message":"成功",
"code":"200"
}
或
{
"data":null,
"message":"未將對象引用到實例",
"code":"-999"
}
代碼中的LogHelper是自己封裝的log4net日志記錄框架,網上有很多集成教程