[英]OnActionExecuted doesn't return response to client in webpi
I want to log all requests (including response) sent to api controller. 我想记录所有发送到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);
}
}
Here is my api controller: 这是我的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());
}
}
If I comment OnActionExecuted
method then response is returned fine. 如果我评论
OnActionExecuted
方法,则响应返回正确。 But with OnActionExecuted
method no response is returned. 但是使用
OnActionExecuted
方法不会返回任何响应。
I was reading response as: 我读的答复是:
string data;
using (var stream = context.Response.Content.ReadAsStreamAsync().Result)
{
if (stream.CanSeek)
{
stream.Position = 0;
}
data = context.Response.Content.ReadAsStringAsync().Result;
}
Response wasn't returned to client because using dispose stream. 由于使用处置流,因此未将响应返回给客户端。
It worked after removing using
: using
删除后,它可以工作:
string data;
var stream = context.Response.Content.ReadAsStreamAsync().Result;
if (stream.CanSeek)
{
stream.Position = 0;
}
data = context.Response.Content.ReadAsStringAsync().Result;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.