2009-11-16 12 views
5

我們在我們的網站中有一些ASPX和HTML文件,並且希望在每個文件的末尾插入一個小的JavaScript。如果我想用HttpModule來做這件事(試圖學習一些新的東西),這是否會出現 - 是否存在明顯的問題?ASP.NET:將內容注入到所有響應流中

public void Init(HttpApplication context) 
{ 
    context.BeginRequest += new EventHandler(context_BeginRequest); 
} 

void context_BeginRequest(object sender, EventArgs e) 
{ 
    var context = HttpContext.Current; 

    if (!isAspxOrHtmlFile(context.Request.Path) 
    { 
     return; 
    } 

    var javascript = ... 

    using (var writer = new StringWriter()) 
    { 
     context.Server.Execute(context.Request.Path, writer); 
     context.Response.ContentType = "text/html"; 
     context.Response.Write(writer.GetStringBuilder().ToString() + javascript); 
    } 

    context.Response.End(); 
} 

回答

4

你可能知道簡單的方法是使用靜態的自定義用戶控件在您的網站母版頁文件,就像老SSI包含文件,對不對?

關於HttpModule,你應該知道內容不是HTML,但似乎你已經通過使用isAspxOrHtmlFile()刪除此內容。對我來說似乎很好。

+1

是的,我相信有更好的方法來做到這一點,我只是用它作爲一個例子來熟悉HttpModules。謝謝 :) – JamesBrownIsDead 2009-11-16 18:11:43