目前已在比IIS6或5你怎麼寫的HttpModules在IIS7一些變化,所以它可能是我的建議,如果你正在使用IIS7是無效的。
如果您當前使用的靜態屬性HttpContext可以獲得對當前上下文的引用。 HttpContext類具有Request(HttpRequest類型)和Response(HttpResponse)兩個屬性,並且取決於您正在處理哪個事件(Application.EndRequest可能?),您可以對這些對象執行各種操作。
如果您想更改正在交付的頁面的內容,您可能希望儘可能晚地做到這一點,因此對EndRequest事件的響應可能是最好的做法。
通過檢查Request.Url屬性(可能與System.IO.Path類一起)來檢查請求的文件類型。試試這樣:
string requestPath = HttpContext.Current.Request.Url.AbsolutePath;
string extension = System.IO.Path.GetExtension(requestPath);
bool isAspx = extension.Equals(".aspx");
修改內容比較困難。您可能可以在Context對象的其中一個事件中執行此操作,但我不確定。
一種可能的方法是編寫自己的Cusom頁面派生類,它將檢查Context.Items集合中的值。如果找到了這個值,你可以爲一個PlaceHolder對象添加一個標籤,並將該標籤的文本設置爲你想要的。
像這樣的東西應該工作:
下面的代碼添加到一個HTTP模塊派生類:
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
void BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
string requestPath = HttpContext.Current.Request.Url.AbsolutePath;
string extension = System.IO.Path.GetExtension(requestPath);
bool isAspx = extension.Equals(".aspx");
if (isAspx)
{
// Add whatever you need of custom logic for adding the content here
context.Items["custom"] = "anything here";
}
}
那你下面的類添加到App_Code文件夾:
public class CustomPage : System.Web.UI.Page
{
public CustomPage()
{ }
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Context.Items["custom"] == null)
{
return;
}
PlaceHolder placeHolder = this.FindControl("pp") as PlaceHolder;
if (placeHolder == null)
{
return;
}
Label addedContent = new Label();
addedContent.Text = Context.Items["custom"].ToString();
placeHolder .Controls.Add(addedContent);
}
}
然後你可以像這樣修改你的頁面:
public partial class _Default : CustomPage
請注意,繼承已從System.Web.UI.Page更改爲CustomPage。
最後,將PlaceHolder對象添加到您希望自定義內容的aspx文件中。
它是否爲「p」給出空引用?處理程序不是一個頁面? – 2008-12-02 08:02:34
你還可以發佈異常的堆棧跟蹤嗎?這可能有助於診斷問題。 – csgero 2008-12-02 08:42:51
該代碼不起作用,因爲該頁面對象在請求開始時不可用,請嘗試使用PreRequestHandlerExecute代替 – haze4real 2010-06-04 14:37:28