记录web api的request以及response(即写log)
https://www.cnblogs.com/felixnet/p/5689501.html
https://blog.csdn.net/Vblegend_2013/article/details/83446229
https://stackoverflow.com/questions/27176329/web-api-request-content-empty
https://forums.asp.net/t/2127541.aspx?Get+Http+Raw+Request+and+Response 这个里面提到了DelegatingHandler
https://www.infoworld.com/article/3211590/how-to-log-request-and-response-metadata-in-aspnet-web-api.html 这个里面提到了DelegatingHandler
https://github.com/aspnet/AspNetWebStack/issues/150
综合上面几个链接,日志应该使用delegating handler里面处理。(ActionFilter里面,http request的content已经被读取过了,需要像第一个链接里面一样,先重置回去,再读,比较麻烦)
string requestMessage = requestContent.ReadAsStringAsync().Result; //request raw
string responseMessage = response.ToString(); //response raw
自己写的版本
public class LogHandler : DelegatingHandler
{
private string _requestId;
private readonly string _newLine = Environment.NewLine; protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
_requestId = DateTime.Now.Ticks.ToString();
var requestBody = request.Content.ReadAsStringAsync().Result;
LogUtil.CreateLog(LogLevel.Message,
$"{_requestId}{_newLine}{request.Method.Method} {request.RequestUri.AbsoluteUri} HTTP/{request.Version}{_newLine}{requestBody}"); var response = await base.SendAsync(request, cancellationToken);
string responseBody = response.Content.ReadAsStringAsync().Result;
LogUtil.CreateLog(LogLevel.Message, $"{_requestId}{_newLine}HTTP/{response.Version} {(int)response.StatusCode} {response.StatusCode}{_newLine}{responseBody}{_newLine}{_newLine}");
return response;
}
}
有ReadAsAsync扩展方法,自动进行类型的转换
var apiRequest = request.Content.ReadAsAsync<ApiRequest<dynamic>>().Result;
OwinRequestScopeContext.Current.Items["CountryCode"] = apiRequest.Header.OpCo;
这个地方如果需要重复读取数据的话
https://stackoverflow.com/questions/26942514/multiple-calls-to-httpcontent-readasasync
If you want to read again and again, you would probably want to read as stream and seek to beginning every time you read the stream.
But then if you want to do what do you now but get the second read working, you can seek to the beginning of the stream, after the first read, like this.
await httpContent.LoadIntoBufferAsync();
var X = await httpContent.ReadAsAsync<T>(); Stream stream = await httpContent.ReadAsStreamAsync();
stream.Seek(, SeekOrigin.Begin); var Y = await httpContent.ReadAsAsync<Dictionary<string, object>>();
中间的stream不需要using,否则会遇到这种错误
HTTP/1.1 400 BadRequest
{"Message":"The request is invalid.","ModelState":{"request":["Stream was not readable."]}}
记录web api的request以及response(即写log)的更多相关文章
- WebApi官网学习记录---web api中的路由
如果一条路由匹配,WebAPI选择controller和action通过如下方式: 1.找到controller,将"controller"赋值给{controller}变量 2. ...
- .net core web api 获取request body的纯文本
本文代码 https://github.com/wuhaibo/readPlainTextDotNetCoreWepApi 总有些时候我们希望获得Request body 的纯文本 那么怎么做呢?很简 ...
- Web API使用记录系列(一)创建API项目与基本配置
本系列文章主要记录Web API使用过程中的一些个人总结,包括创建API项目.基础配置.ApiTestClient使用与HelpPage页面的优化.Owin与OAuth的使用等. 本节主要内容是API ...
- Dynamics CRM2016 Web API之通过实体的primary key查询记录
CRM2016启用了webapi 而弃用了odata,作为码农的我们又开始学习新东西了. 下面是一段简单的查询代码,通过systemuser的primary key来查询一条记录 Web API查询方 ...
- .Net中使用SendGrid Web Api发送邮件(附源码)
SendGrid是一个第三方的解决邮件发送服务的提供商,在国外使用的比较普遍.国内类似的服务是SendCloud.SendGrid提供的发送邮件方式主要是两种, 一种是SMTP API, 一种是Web ...
- ASP.NET Web Api返回对象类型为JSON还是XML
在Umbraco平台上开发过程中,我用WebApi返回JSON result给前端 前端使用React调用这个web api来获取JSON result 我写的web api方法是返回JSON 类型的 ...
- Asp.Net Web API VS Asp.Net MVC
http://www.dotnet-tricks.com/Tutorial/webapi/Y95G050413-Difference-between-ASP.NET-MVC-and-ASP.NET-W ...
- 【ASP.NET Web API教程】2.1 创建支持CRUD操作的Web API
原文 [ASP.NET Web API教程]2.1 创建支持CRUD操作的Web API 2.1 Creating a Web API that Supports CRUD Operations2.1 ...
- 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】
Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...
随机推荐
- 360全景图three.js与Photo-Sphere-Viewer-master 3D全景浏览开发
1.支持WebGL和canvas的浏览器 (IE10, IE11支持, 但在IE里移动图片时很卡, 不一定是全部人都有这情况) 2.Three.js (文件较大, 有官网demo, 可不下载, 下载p ...
- MarkDownPad2 key
MarkDownPad2 key : Soar360@live.com GBPduHjWfJU1mZqcPM3BikjYKF6xKhlKIys3i1MU2eJHqWGImDHzWdD6xhMNLGVp ...
- 如何获取e.printStackTrace()的内容
e.printStackTrace()通常是打印在控制台的,但是,有时候程序上线了需要看这个堆栈的内容就不容易了,一来生产环境打印的东西很多或者很少,二来有时候无法直接查看到,这个时候就需要把这些内容 ...
- 百度地图api定位和导航简写
function locate() { // 百度地图API功能 var map = new BMap.Map("allmap"); // 创建Map实例 var point = ...
- maven的install和deploy的区别
转自:http://blog.csdn.net/u011305680/article/details/51699471 maven package:打包到本项目,一般是在项目target目录下.如果a ...
- onethink重新安装后,还原数据库后,登陆不了解决办法!
在用onethink开发的时候,为了防止修改出错,我会在开发下一个功能的对上一个功能代码整体进行备份,如果出错就返回上一个版本再次修改. 但是会发现一个问题,如果如果返回到上一个版本,重新安装完成之后 ...
- vector库的用法
C++内置的数组支持容器的机制,但是它不支持容器抽象的语义.要解决此问题我们自己实现这样的类.在标准C++中,用容器向量(vector)实现.容器向量也是一个类模板.标准库vector类型使用需要的头 ...
- js 的正则表达式 部分展示test()方法的验证功能
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- js jquery.pagination.js分页
1.使用插件为 jquery.pagination.js ,如果没有这个js文件的话,我可以给发个. 首先引用 jquery.pagination.js (分页js),跟pagination.css( ...
- SaltStack生产案例-服务部署(redis,mysql,apache+php,haproxy+keepalived)
顺序代码资料链接 课上资料.zip 接上篇:SaltStack生产案例-系统初始化 1,redis 主从 2,mysql 主从 2.1 mysql-install.sls (安装 初始化) 2.2 ...