我想记录发送到api控制器的所有请求(包括响应)。
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//my logic to get request and save in logs.
var jsonBody = Utility.GetRequestJSON(actionContext);
Utility.SaveLogAsync(jsonBody);
}
public override void OnActionExecuted(HttpActionExecutedContext actionContext)
{
//my logic to get response and save in logs.
string responseReturned = GetBodyFromRequest(actionContext);
Utility.SaveLogAsync(responseReturned); //data is logged successfully but no response is returned to client.
base.OnActionExecuted(actionContext);
}
}
这是我的api控制器:
[LogActionFilter]
public class ServiceController : ApiController
{
[AcceptVerbs("GET", "POST")]
[HttpGet]
[HttpPost]
public object Login()
{
var jsonBody = Utility.GetRequestJSON(HttpContext.Current);
AccountService _accountService = new AccountService();
return _accountService.Login(jsonBody, Request.GetClientIP());
}
}
如果我评论OnActionExecuted
方法,则返回的响应很好。但是使用OnActionExecuted
方法不会返回任何响应。
答案 0 :(得分:1)
我的读法是:
string data;
using (var stream = context.Response.Content.ReadAsStreamAsync().Result)
{
if (stream.CanSeek)
{
stream.Position = 0;
}
data = context.Response.Content.ReadAsStringAsync().Result;
}
由于使用处置流,因此未将响应返回给客户端。
它在删除using
之后起作用:
string data;
var stream = context.Response.Content.ReadAsStreamAsync().Result;
if (stream.CanSeek)
{
stream.Position = 0;
}
data = context.Response.Content.ReadAsStringAsync().Result;