记录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 创 ...
随机推荐
- Windows Phone 几种页面间传递数据的方式
首先,我们要引用:using Microsoft.Phone.Shell; 第一种: // 导航到新页面 NavigationService.Navigate(new Uri("/Detai ...
- Oracle各种表空间
system表空间:含数据字典信息 sysaux表空间:存储各种oracle应用的元数据(如AWR的操作数据) 创建表空间后,不能改变区尺寸 区尺寸管理:自动分配(AUTOALLOCATE):小段64 ...
- Zabbix邮件告警提示Couldn't resolve host name解决办法
zabbix设置好邮件告警,当有触发时邮件未发送 查看zabbix server日志,提示不能连接邮件发送服务器,但是ping是可以通的
- 南京网络赛G-Lpl and Energy【线段树】
During tea-drinking, princess, amongst other things, asked why has such a good-natured and cute Drag ...
- Only a type can be imported. classname resolves to a package的解决
Only a type can be imported. l1.l2.MyClass resolves to a package ==========这里是解决方案=============== 把生 ...
- Scrapy框架(3)
一.如何提升scrapy框架的爬取效率 增加并发: 默认scrapy开启的并发线程为32个,可以适当进行增加.在settings配置文件中修改CONCURRENT_REQUESTS = 100,并发设 ...
- cocos2d首印象
一. 创建工程 从 2.1.4 版本开始,官方就不再为 VS 提供模板了,逐步在各平台采用统一的 Python 脚本创建跨平台工程. 要创建工程,我们需要先从命令行进入 tools/project-c ...
- 从WW中剥离一个三维场景框架
从WW中剥离一个三维场景框架,初步实现的一个.可以绘制一个三角形,但是不能够控制摄像机,没有增加鼠标事件.没有投影,世界变幻之类的东西.以后会不断学习逐步增加进来. 下载地址 下载V1.0.0.2
- 驼峰命名和下划线命名互转php实现
驼峰命名和下划线命名经常需要互转,下面提供两种php的实现方式.第一种方法效率相对差一些,实现方式如下: //驼峰命名转下划线命名 function toUnderScore($str) { $dst ...
- Spark中ml和mllib的区别
转载自:https://vimsky.com/article/3403.html Spark中ml和mllib的主要区别和联系如下: ml和mllib都是Spark中的机器学习库,目前常用的机器学习功 ...