问题描述
我有一个做了POST如下面
I have a method that does a POST like below
var response = await client.PostAsJsonAsync(url, entity);
if (response.IsSuccessStatusCode)
{
// read the response as strongly typed object
return await response.Content.ReadAsAsync<T>();
}
我的问题是我怎么能获得该贴得到从实体对象的实际JSON。我想日志被张贴JSON,所以这将是不错的,如果没有我不得不做一个JSON序列化自己。
My question is how can I obtain the actual JSON that got posted from the entity object. I would like to log the JSON that gets POSTED, so it will be nice to have that without me having to do a json serialize myself.
推荐答案
如何,你可以做这样的一个例子:
An example of how you could do this:
一些注意事项:
-
LoggingHandler
拦截请求它处理它HttpClientHandler
并最终写入线前。
LoggingHandler
intercepts the request before it handles it toHttpClientHandler
which finally writes to the wire.
PostAsJsonAsync
扩展内部创建一个 ObjectContent
当 ReadAsStringAsync()
是所谓的 LoggingHandler
,它会导致格式化在 ObjectContent
序列化对象,这就是你看到的JSON内容的原因。
PostAsJsonAsync
extension internally creates an ObjectContent
and when ReadAsStringAsync()
is called in the LoggingHandler
, it causes the formatterinside ObjectContent
to serialize the object and that's the reason you are seeing the content in json.
日志处理程序:
public class LoggingHandler : DelegatingHandler
{
public LoggingHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Console.WriteLine("Request:");
Console.WriteLine(request.ToString());
if (request.Content != null)
{
Console.WriteLine(await request.Content.ReadAsStringAsync());
}
Console.WriteLine();
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Console.WriteLine("Response:");
Console.WriteLine(response.ToString());
if (response.Content != null)
{
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
Console.WriteLine();
return response;
}
}
链上面LoggingHandler与HttpClient的
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
HttpResponseMessage response = client.PostAsJsonAsync(baseAddress + "/api/values", "Hello, World!").Result;
输出:
Request:
Method: POST, RequestUri: 'http://kirandesktop:9095/api/values', Version: 1.1, Content: System.Net.Http.ObjectContent`1[
[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Headers:
{
Content-Type: application/json; charset=utf-8
}
"Hello, World!"
Response:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Fri, 20 Sep 2013 20:21:26 GMT
Server: Microsoft-HTTPAPI/2.0
Content-Length: 15
Content-Type: application/json; charset=utf-8
}
"Hello, World!"
这篇关于在使用日志请求/响应消息的HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!