Reputation: 910
I am creating an action filter that should read the response returned by an action, collect some data from it then log it, but I can't find anywhere where I could read the response body. I tried the following code to access a property name OutputStream at the respone in an HttpContext, but I keep getting error saying that Length property and Read method are not supported for this stream.
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
byte[] buffer = new byte[filterContext.HttpContext.Response.OutputStream.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = filterContext.HttpContext.Response.OutputStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
string html = Encoding.UTF8.GetString(ms.ToArray());
}
}
Upvotes: 1
Views: 2621
Reputation: 2083
I can not extract from "Stream", so I decided to use "Result Data" to get the data to my Log.
public class LogResultFilter : IActionFilter, IResultFilter
{
public void OnResultExecuted(ResultExecutedContext filterContext)
{
var responseBody = string.Empty;
if (filterContext.Result is ViewResultBase)
{
responseBody = new JavaScriptSerializer().Serialize(((ViewResultBase)filterContext.Result).ViewData);
}
if (filterContext.Result is JsonResult)
{
responseBody = new JavaScriptSerializer().Serialize(((JsonResult)filterContext.Result));
}
// Continue...
Upvotes: 1