I was trying to calculate the length of a HTTP Response
.
Seems the stream doesn\'t want to play. (no read allowed. and the Content-Length doesn\'t seem set)
I w
You could write a custom Response filter:
public class ResponseLengthCalculatingStream: MemoryStream
{
private readonly Stream responseStream;
private long responseSize = 0;
public ResponseLengthCalculatingStream(Stream responseStream)
{
this.responseStream = responseStream;
}
public override void Write(byte[] buffer, int offset, int count)
{
this.responseSize += count;
this.responseStream.Write(buffer, offset, count);
}
public override void Flush()
{
var responseSize = this.responseSize;
// Here you know the size of the response ...
base.Flush();
}
}
and register it in your Global.asax
:
protected void Application_BeginRequest()
{
Context.Response.Filter = new ResponseLengthCalculatingStream(Context.Response.Filter);
}
And if you wanted to apply this filter only on particular controller actions you could write a custom action filter instead of applying it in the BeginRequest event in Global.asax:
public class ResponseLengthCapturingAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.HttpContext.Response;
response.Filter = new ResponseLengthCalculatingStream(response.Filter);
}
}
and then all that's left is decorate the controller action with the corresponding action filter:
[ResponseLengthCapturing]
public ActionResult Index()
{
...
return View();
}