c# - 需要将 asp.net webapi 2 请求和响应正文记录到数据库

标签 c# asp.net-web-api

我正在使用托管在 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/

相关文章:

c# - Visual Studio 自动格式损坏

c# - 在 asp.net core 中将 index.html 设置为默认页面

c# - 延迟构建请求

c# - GenericType <T> 传递给 WEB-API

asp.net-web-api - 为什么 System.Web.Http.OData 未列出?

c# - 在调用方法中模拟局部变量

c# - FileContentResult 有效,但下载到字节数组无效

c# - 对使用 IdentityServer3 进行承载身份验证的 ASP.NET WebAPI Controller 进行集成测试

asp.net-mvc-4 - 我可以向 ApiController 添加操作作为扩展方法吗?

c# - ASP.NET Web API OData - 将 DTO 查询转换为实体查询