我正在使用托管在 IIS 上的 Microsoft Asp.net WebApi2。我只是想记录每个帖子的请求正文(XML 或 JSON)和响应正文。
这个项目或处理帖子的 Controller 没有什么特别之处。我对使用 nLog、elmah、log4net 等日志记录框架或 Web API 的内置跟踪功能不感兴趣,除非有必要这样做。
我只是想知道将日志记录代码放在哪里以及如何从传入和传出请求和响应中获取实际的 JSON 或 XML。
我的 Controller 发布方法:
public HttpResponseMessage Post([FromBody])Employee employee)
{
if (ModelState.IsValid)
{
// insert employee into to the database
}
}
最佳答案
我建议使用 DelegatingHandler
。这样您就无需担心 Controller 中的任何日志记录代码。
public class LogRequestAndResponseHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Content != null)
{
// 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;
}
}
只需将 Trace.WriteLine
替换为您的日志记录代码,然后在 WebApiConfig
中注册处理程序,如下所示:
config.MessageHandlers.Add(new LogRequestAndResponseHandler());
这是 Message Handlers 的完整 Microsoft 文档.
关于c# - 需要将 asp.net webapi 2 请求和响应正文记录到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23660340/