目前已在比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