与 IIS6 或 5 相比,您在 IIS7 中编写 HttpModules 的方式发生了一些变化,因此如果您使用的是 IIS7,我的建议可能无效。
如果您使用 HttpContext 的 Current 静态属性,您可以获得对当前上下文的引用。HttpContext 类具有请求(HttpRequest 类型)和响应(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 对象的事件之一中做到这一点,但我不确定。
一种可能的方法是编写您自己的自定义页面派生类,该类将检查 Context.Items 集合中的值。如果找到此值,您可以将标签添加到 PlaceHolder 对象并将标签的文本设置为您想要的任何内容。
像这样的东西应该工作:
将以下代码添加到 HttpModule 派生类:
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 文件中。