我尝试使用 ihttpmodule 将 js 注入到页面(到标签)。
但js没有注入。
我做了什么:
这一页:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MyTempProject._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Temp</title>
</head>
<body>
<form id="form1">
<div>
</div>
</form>
</body>
</html>
ihttp模块:
public class MyExtensionModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
string script = "/Scripts/jquery-1.5.1.js";
if (page.Header != null)
{
string scriptTag = String.Format("<script language=\"javascript\" type=\"text/javascript\" src=\"{0}\"></script>\n", script); page.Header.Controls.Add(new LiteralControl(scriptTag));
}
else if (!page.ClientScript.IsClientScriptIncludeRegistered(page.GetType(), script)) page.ClientScript.RegisterClientScriptInclude(page.GetType(), script, script);
}
}
#endregion
}
The 开始请求事件还为时过早,无法挂钩到页面。在请求周期的这一点上,IIS/ASP.NET 甚至还没有决定将您的请求映射到任何内容。所以你可能应该尝试类似的东西PostMap请求处理程序 event.
然而,这还不是全部:此时页面(如果有的话)尚未执行。这发生在预请求处理程序执行 and PostRequestHandler执行事件。所以 Pre... 太早,而 Post... 太晚了。您最好的选择是挂钩页面事件,例如预渲染完成,然后执行您的注射。
public void Init(HttpApplication context)
{
context.PostMapRequestHandler += OnPostMapRequestHandler;
}
void OnPostMapRequestHandler(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
page.PreRenderComplete += OnPreRenderComplete;
}
}
void OnPreRenderComplete(object sender, EventArgs e)
{
Page page = (Page) sender;
// script injection here
}
CAUTION:很少有人还在使用它们,但是服务器执行 and 服务器传输 不执行任何管道事件。所以这样的子请求永远不能用IHttp模块.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)