2009-01-27 21 views
7

我有一個IIS 6的ISAPI篩選器,它使用響應的字節發送字段進行一些自定義處理。我想更新爲IIS 7,但我遇到了一個問題。沒有一個IIS 7事件似乎有權訪問內容長度,發送的字節數或任何可以讓我計算內容長度或發送字節的數據。 (我知道內容長度頭和發送的字節是不一樣的,但要麼會爲此目的而工作。)IIS 7託管模塊無法獲取內容長度或字節發送

從我可以告訴,內容長度頭被HTTP.SYS添加後託管模塊已經完成執行。現在我有一個在EndRequest上運行的事件處理程序。如果我可以得到輸出流,我可以計算自己需要的東西,但是管理的管道似乎也無法訪問它。

是否有某種獲取託管管道中發送的內容長度或字節的方法?否則,有什麼方法可以計算從託管管道中可用對象發送的內容長度或字節數?

+0

有什麼我可以添加,這將有助於回答這個問題? – 2009-02-05 21:16:16

回答

7

要獲取發送的字節,您可以使用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; } 
    } 
} 
+0

感謝您提供非常完整的答案和代碼示例。現在我只需要一個插入它的機會並嘗試一下。 – 2009-02-09 15:45:40