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)的更多相关文章

  1. WebApi官网学习记录---web api中的路由

    如果一条路由匹配,WebAPI选择controller和action通过如下方式: 1.找到controller,将"controller"赋值给{controller}变量 2. ...

  2. .net core web api 获取request body的纯文本

    本文代码 https://github.com/wuhaibo/readPlainTextDotNetCoreWepApi 总有些时候我们希望获得Request body 的纯文本 那么怎么做呢?很简 ...

  3. Web API使用记录系列(一)创建API项目与基本配置

    本系列文章主要记录Web API使用过程中的一些个人总结,包括创建API项目.基础配置.ApiTestClient使用与HelpPage页面的优化.Owin与OAuth的使用等. 本节主要内容是API ...

  4. Dynamics CRM2016 Web API之通过实体的primary key查询记录

    CRM2016启用了webapi 而弃用了odata,作为码农的我们又开始学习新东西了. 下面是一段简单的查询代码,通过systemuser的primary key来查询一条记录 Web API查询方 ...

  5. .Net中使用SendGrid Web Api发送邮件(附源码)

    SendGrid是一个第三方的解决邮件发送服务的提供商,在国外使用的比较普遍.国内类似的服务是SendCloud.SendGrid提供的发送邮件方式主要是两种, 一种是SMTP API, 一种是Web ...

  6. ASP.NET Web Api返回对象类型为JSON还是XML

    在Umbraco平台上开发过程中,我用WebApi返回JSON result给前端 前端使用React调用这个web api来获取JSON result 我写的web api方法是返回JSON 类型的 ...

  7. 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 ...

  8. 【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 ...

  9. 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 创 ...

随机推荐

  1. sencha touch 入门系列 (九)sencha touch 视图组件简介

    对于一个普通用户来说,你的项目就是一组简单的视图集合,用户直接通过跟视图进行交互来操作你的应用,对于一个开发人员来说,视图是一个项目的入口,虽然大部分时候最有价值的部分是在model层和control ...

  2. c# 计算文字高度

    SizeF sizeF = g.MeasureString(listBox1.Items[e.Index].ToString(), e.Font, listBox1.Width);

  3. 【JavaScript算法】---希尔排序

    一.什么是希尔排序 希尔排序(Shell's Sort)是插入排序的一种又称“缩小增量排序”,是直接插入排序算法的一种更高效的改进版本.   思路:      希尔排序是把记录按下标的一定增量分组,对 ...

  4. 170714、springboot编程之多数据源切换(动态)

    (1)新建maven java project; 新建一个maven project,取名为:spring-boot-multi-ds (2)在pom.xml添加依赖包: 在pom.xml文件中加入依 ...

  5. codeforces#510 Div2

    pre过了三题 后来A题被hack了 B题终测挂了 两题其实都是有一个小细节没有处理好 中间C还因为cinT了一次 唉本来打的还不错的 还是太菜了 继续加油吧 A-Benches 有n张椅子 原来第i ...

  6. ArrayList遍历的三种方式 array arrayList转换

    ArrayList遍历的三种方式 - 呵呵静 - 博客园 https://www.cnblogs.com/mjyung/p/6725182.html

  7. 禁止输入emoji表情

    三个文本框textField UITextView都要禁止苹果自带emoji 后来发现是原来写的方法不能覆盖所有的表情,新增的表情过滤不掉,只好再加了一个方法 http://www.jianshu.c ...

  8. Android中的Handler及它所引出的Looper、MessageQueue、Message

    0.引入 0.1.线程间通信的目的 首先,线程间通信要交流些什么呢? 解答这个问题要从为什么要有多线程开始,需要多线程的原因大概有这些 最早也最基本:有的任务需要大量的时间,但其实并不占用计算资源,比 ...

  9. MVC模式:python案例

    quotes = ('A man is not complete until he is married. Then he is finished.', 'As I said before, I ne ...

  10. POJ1273:Drainage Ditches(最大流入门 EK,dinic算法)

    http://poj.org/problem?id=1273 Description Every time it rains on Farmer John's fields, a pond forms ...