从IhttpModule中注入js

Dav*_*eli 7 c# asp.net 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>
Run Code Online (Sandbox Code Playgroud)

ihttpmodule:

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
    }
Run Code Online (Sandbox Code Playgroud)

Rub*_*ben 8

的BeginRequest事件是太早挂接到一个页面.在请求周期的那一点上,IIS/ASP.NET甚至没有决定将您的请求映射到任何东西.所以你应该尝试类似PostMapRequestHandler事件.

但是,这并不是全部:在那一点上,页面(如果有的话)还没有执行.这恰好发生在PreRequestHandlerExecutePostRequestHandlerExecute事件之间.所以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
}
Run Code Online (Sandbox Code Playgroud)

注意:很少有人仍然使用它们,但Server.ExecuteServer.Transfer 不会执行任何管道事件.因此,永远不会使用IHttpModule捕获此类子请求.