我正在使用托管在IIS上的Microsoft Asp.net WebApi2。我只想记录每个帖子的请求正文(XML或JSON)和响应正文。
这个项目和处理post的控制器没有什么特别之处。除非有必要,否则我对使用nLog、elmah、log4net等日志记录框架或web的内置跟踪功能不感兴趣。
我只是想知道把我的日志代码放在哪里,以及如何从传入和传出的请求和响应中获取实际的JSON或XML。
我的控制器post方法:
public HttpResponseMessage Post([FromBody])Employee employee)
{
if (ModelState.IsValid)
{
// insert employee into to the database
}
}
发布于 2014-05-15 01:01:03
我建议使用DelegatingHandler
。然后,您将不需要担心控制器中的任何日志记录代码。
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文档。
发布于 2014-05-15 02:28:06
你可以选择创建一个动作过滤器,并用它来装饰你的WebApiController/ApiMethod。
过滤器属性
public class MyFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.Request.Method == HttpMethod.Post)
{
var postData = actionContext.ActionArguments;
//do logging here
}
}
}
WebApi控制器
[MyFilterAttribute]
public class ValuesController : ApiController{..}
或
[MyFilterAttribute]
public void Post([FromBody]string value){..}
希望这能有所帮助。
发布于 2014-05-15 01:01:23
访问请求消息很容易。您的base class, ApiController
包含.Request
property,顾名思义,它包含解析形式的请求。您只需检查要记录的内容,并将其传递给您的日志记录工具。如果你只需要为一个或几个人做这件事,你可以把这段代码放在你动作的开始。
如果您需要在所有操作上执行此操作(所有操作都意味着不只是几个可管理的操作),那么您可以做的就是覆盖.ExecuteAsync
方法来捕获控制器的每个操作调用。
public override Task<HttpResponseMessage> ExecuteAsync(
HttpControllerContext controllerContext,
CancellationToken cancellationToken
)
{
// Do logging here using controllerContext.Request
return base.ExecuteAsync(controllerContext, cancellationToken);
}
https://stackoverflow.com/questions/23660340
复制相似问题