我們一般用日志記錄每次Action的請求和響應,方便接口出錯后排查,不過如果每個Action方法內都寫操作日志太麻煩,而且客戶端傳遞了錯誤JSON或XML,沒法對應強類型參數,請求沒法進入方法內,
把日志記錄操作放在一個ActionFilter即可。
[AttributeUsageAttribute(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public class ApiActionAttribute : ActionFilterAttribute { private string _requestId; public override void OnActionExecuting(HttpActionContext actionContext) { base.OnActionExecuting(actionContext); _requestId = DateTime.Now.Ticks.ToString(); //獲取請求數據 Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result; string requestDataStr = ""; if (stream != null && stream.Length > 0) { stream.Position = 0; //當你讀取完之后必須把stream的讀取位置設為開始 using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8)) { requestDataStr = reader.ReadToEnd().ToString(); } } //[POST_Request] {requestid} http://dev.localhost/messagr/api/message/send {data} Logger.Instance.WriteLine("[{0}_Request] {1} {2}\r\n{3}", actionContext.Request.Method.Method, _requestId, actionContext.Request.RequestUri.AbsoluteUri, requestDataStr); } public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { base.OnActionExecuted(actionExecutedContext); string responseDataStr = actionExecutedContext.Response.Content.ReadAsStringAsync().Result; //[POST_Response] {requestid} {data} Logger.Instance.WriteLine("[{0}_Response] {1}\r\n{2}", actionExecutedContext.Response.RequestMessage.Method, _requestId, responseDataStr); } }
_requestId 是用來標識請求的,根據它可以找到對應的Request與Response,便於排查。在Action上聲明:
[Route("send_email")] [HttpPost] [ApiAction] [ApiException] public async Task<SendMessageResponseDto> Send(SendEmailMessageRequestDto dto) { //... }