要获取发送的字节,您可以使用该HttpResponse.Filter
属性。正如 MSDN 文档所说,此属性获取或设置一个包装过滤器对象,该对象用于在传输之前修改 HTTP 实体主体。
您可以创建一个System.IO.Stream
包装现有HttpResponse.Filter
流的新流,并在传递它们之前计算传入方法的字节数Write
。例如:
public class ContentLengthModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += OnBeginRequest;
context.EndRequest += OnEndRequest;
}
void OnBeginRequest(object sender, EventArgs e)
{
var application = (HttpApplication) sender;
application.Response.Filter = new ContentLengthFilter(application.Response.Filter);
}
void OnEndRequest(object sender, EventArgs e)
{
var application = (HttpApplication) sender;
var contentLengthFilter = (ContentLengthFilter) application.Response.Filter;
var contentLength = contentLengthFilter.BytesWritten;
}
public void Dispose()
{
}
}
public class ContentLengthFilter : Stream
{
private readonly Stream _responseFilter;
public int BytesWritten { get; set; }
public ContentLengthFilter(Stream responseFilter)
{
_responseFilter = responseFilter;
}
public override void Flush()
{
_responseFilter.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
return _responseFilter.Seek(offset, origin);
}
public override void SetLength(long value)
{
_responseFilter.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count)
{
return _responseFilter.Read(buffer, offset, count);
}
public override void Write(byte[] buffer, int offset, int count)
{
BytesWritten += count;
_responseFilter.Write(buffer, offset, count);
}
public override bool CanRead
{
get { return _responseFilter.CanRead; }
}
public override bool CanSeek
{
get { return _responseFilter.CanSeek; }
}
public override bool CanWrite
{
get { return _responseFilter.CanWrite; }
}
public override long Length
{
get { return _responseFilter.Length; }
}
public override long Position
{
get { return _responseFilter.Position; }
set { _responseFilter.Position = value; }
}
}