写一个ActionFilter检测WebApi接口请求和响应
2016-07-20 19:40
495 查看
我们一般用日志记录每次Action的请求和响应,方便接口出错后排查,不过如果每个Action方法内都写操作日志太麻烦,而且客户端传递了错误JSON或XML,没法对应强类型参数,请求没法进入方法内,
把日志记录操作放在一个ActionFilter即可。
_requestId 是用来标识请求的,根据它可以找到对应的Request与Response,便于排查。在Action上声明:
把日志记录操作放在一个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) { //... }
相关文章推荐
- VirtualBox的安装与使用
- Axure 学习笔记(二)
- [LeetCode] 39. Combination Sum
- angular的service服务和factory服务
- Bzoj2839:集合计数:组合数学+容斥
- Graph Coloring【NOIP2016提高A组模拟7.20】
- angular的provider服务
- Java Stack源码分析
- UVA 572 Oil Deposits
- shell脚本 - 完成商品销量排行的统计:倒插数据库法
- leetcode 151 Reverse Words in a String java 算法
- HDU 5029 Relief grain(恶心的树链剖分 + 线段树)
- [leetcode] 343. Integer Break
- 编译器之语义分析
- Biker's Trip Odometer(求平均速度)
- Python从入门到放弃(三):基本语句和语法
- __bridge,__bridge_retained和__bridge_transfer的意思,区别与使用
- python运行不了 AttributeError: module object has no attribute getdefaultlocale
- 内存管理
- clipchildren 咸鱼app 中间 图标很大的 底部 tab栏 实现方案