写一个ActionFilter检测WebApi接口请求和响应

我们一般用日志记录每次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 > )
{
stream.Position = ; //当你读取完之后必须把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)
{
//...
}
上一篇:一个简单的Post Get请求


下一篇:mysql连接不上Uncaught exception 'PDOException' with message 'could not find driver