Asp.net web api OnActionx27;t在webpi中返回对客户端的响应
我想记录发送到api控制器的所有请求(包括响应)Asp.net web api OnActionx27;t在webpi中返回对客户端的响应,asp.net-web-api,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.GetRe
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());
}
}
如果我对ActionExecuted方法进行注释,则返回的响应很好。但是使用
OnActionExecuted
方法时,不会返回响应 我的反应是:
string data;
using (var stream = context.Response.Content.ReadAsStreamAsync().Result)
{
if (stream.CanSeek)
{
stream.Position = 0;
}
data = context.Response.Content.ReadAsStringAsync().Result;
}
由于使用dispose stream,响应未返回到客户端。使用删除
后,它工作:
string data;
var stream = context.Response.Content.ReadAsStreamAsync().Result;
if (stream.CanSeek)
{
stream.Position = 0;
}
data = context.Response.Content.ReadAsStringAsync().Result;