[英]Access to session variables from IHttpModule's OnBeginRequest method
[英]Inject js from IhttpModule
我試圖通過使用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>
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
}
BeginRequest事件對於掛鈎頁面來說為時尚早。 在請求周期的那一點上,IIS / ASP.NET甚至沒有決定將您的請求映射到任何東西。 所以你應該嘗試類似PostMapRequestHandler事件。
但是,這並不是全部:在那一點上,頁面(如果有的話)還沒有執行。 這恰好發生在PreRequestHandlerExecute和PostRequestHandlerExecute事件之間。 所以Pre ...太早了,Post ...太晚了。 最好的辦法是掛鈎一個頁面事件,如PreRenderComplete ,然后執行注入。
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
}
注意:很少有人仍然使用它們,但Server.Execute和Server.Transfer 不會執行任何管道事件 。 因此,永遠不會使用IHttpModule捕獲此類子請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.