https://stackoverflow.com/questions/23660340/need-to-log-asp-net-webapi-2-request-and-response-body-to-a-database

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

 拦截api的请求,并进行处理

I would recommend using a DelegatingHandler. Then you will not need to worry about any logging code in your controllers.

public class LogRequestAndResponseHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// log request body
string requestBody = await request.Content.ReadAsStringAsync();
Trace.WriteLine(requestBody); // let other handlers process the request
var result = await base.SendAsync(request, cancellationToken); if (result.Content != null)
{
// once response body is ready, log it
var responseBody = await result.Content.ReadAsStringAsync();
Trace.WriteLine(responseBody);
} return result;
}
}

Just replace Trace.WriteLine with your logging code and register the handler in WebApiConfig like this:

config.MessageHandlers.Add(new LogRequestAndResponseHandler());

最新文章

  1. HTTP Cache
  2. 【菜鸟玩Linux开发】通过MySQL自动同步刷新Redis
  3. Linq使用Distinct删除重复数据时如何指定所要依据的成员属性zz
  4. Oracle 安装 INS-30131错误。
  5. Linux系统产生随机数的3种方法
  6. Android实现拖动进度条改变图片透明度
  7. php--opp--2.什么是类,什么是对象,类和对象这间的关系
  8. Hibernate检索方式 分类: SSH框架 2015-07-10 22:10 4人阅读 评论(0) 收藏
  9. Tkinter教程之Canvas篇(4)
  10. SharePoint 学习记事(三)
  11. 如何实现Android重启应用程序代码 ?
  12. OGRE插件设计-Texture与GLTexture
  13. C语言函数参数压栈顺序为何是从右到左?(从左向右的话,碰到printf的会陷入死循环)
  14. 移动webAPP前端开发技巧汇总2
  15. C#中委托和事件的区别
  16. Python__装饰器练习题
  17. frameset基础了解
  18. spring boot整合 springmvc+mybatis
  19. 总结几个常用的系统安全设置(含DenyHosts)
  20. RHEL7-openldap安装配置一(服务器端安装配置)

热门文章

  1. 简述synchronized和java.util.concurrent.locks.Lock异同
  2. 【BZOJ2212】[Poi2011]Tree Rotations 线段树合并
  3. SetForegroundWindow以及 如何将一个某个窗口提到最顶层(转)
  4. Fiddler 抓包工具使用详解
  5. 修改/etc/hosts 云服务器 没有做外网转内网的优化
  6. 容灾 RPO RTO
  7. 文件操作 - 三元运算/chardet/文件操作r w/文件的操作方法
  8. 错误0x80070522:客户端没有所需的特权
  9. docker 构建镜像 centos7 nginx php
  10. 使用from __future__ import unicode_literals时要注意的问题