我有一个名为Log的属性,它尝试将请求和响应的内容记录到文本文件中.我把它放在我的控制器上以涵盖所有动作.在LogAttribute中,我正在将内容读取为字符串(ReadAsStringAsync),因此我不会丢失请求正文.
public class LogAttribute : ActionFilterAttribute
{
// ..
public override void OnActionExecuting(HttpActionContext actionContext)
{
// stuff goes here
var content = actionContext.Request.Content.ReadAsStringAsync().Result;
// content is always empty because request body is cleared
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// other stuff goes here
var content = actionContext.Request.Content.ReadAsStringAsync().Result;
// content is always empty because request body is cleared
}
// ..
}
Run Code Online (Sandbox Code Playgroud)
另一方面,我在我的动作参数类之前放置了FromBody属性以利用它的好处.
[Log]
public class SomethingController
{
public HttpResponseMessage Foo([FromBody] myModel)
{
// something
}
}
Run Code Online (Sandbox Code Playgroud)
问题是ActionExecuting或ActionExecuted中的内容始终为空.
我认为这是因为FromBody在我的Log属性之前运行,而不像它们在代码中的顺序.我再次认为是因为根据动作参数(路径处理)找到了请求的最佳动作/控制器匹配.之后我的请求正文被清除,因为请求正文在WebApi中是非缓冲的. …