OnActionExecuted不会将响应返回给webpi中的客户端

时间:2018-07-04 07:14:08

标签: asp.net-web-api

我想记录发送到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方法不会返回任何响应。

1 个答案:

答案 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;