用于写出对响应的 JavaScript 脚本引用的 HttpModule
在我的页面上的 Page_Load 事件中,我将字符串集合添加到 Context 对象。我有一个 HttpModule,它将触发 EndRequest 并检索字符串集合。然后我要做的就是写出一个脚本引用标签(基于字符串集合)到响应中。问题是页面读取脚本引用但不检索文件的内容(我想是因为这发生在 EndRequest 事件中)。我无法触发 BeginRequest 事件,因为我无权访问 Context Items 集合。
我还尝试注册一个 HttpHandler 来处理脚本引用的请求,但我无法从那里访问 Context.Items 中的字符串集合。有什么建议吗?
页面加载:
protected void Page_Load(object sender, EventArgs e)
{
Context.Items.Add("ScriptFile", "/UserControls.js");
}
Http模块:
public void OnEndRequest(Object s, EventArgs e)
{
HttpApplication app = s as HttpApplication;
object script = app.Context.Items["ScriptFile"];
app.Response.Write("<script type='text/javascript' src='" + script + "'></script>");
}
On my page in the Page_Load event I add a collection of strings to the Context object. I have an HttpModule that will fire EndRequest and retrieve the collection of strings. What I then do is write out a script reference tag (based on the collection of strings) to the response. The problem is that the page reads the script reference but doesn't retrieve the contents of the file (I imagine because this is occurring in the EndRequest event). I can't fire the BeginRequest event because I won't have access to the Context Items collection.
I tried to also registering an HttpHandler which Processes the request of the script reference but I can't access the collection of strings in the Context.Items from there. Any suggestions?
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
Context.Items.Add("ScriptFile", "/UserControls.js");
}
HttpModule:
public void OnEndRequest(Object s, EventArgs e)
{
HttpApplication app = s as HttpApplication;
object script = app.Context.Items["ScriptFile"];
app.Response.Write("<script type='text/javascript' src='" + script + "'></script>");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,我相当确定这不是放置标签的有效位置。
其次,为什么要重新发明轮子?您已经拥有 ScriptManager 和将脚本代码注入 ASP.NET 输出的成熟方法。为什么这需要在 EndRequest 期间发生?这可能应该在页面级别处理。
First off, I'm fairly certain this is not a valid place to put tags.
Second, why are you re-inventing the wheel? You already have the ScriptManager and well-established methods of injecting script code into ASP.NET output. Why does this need to happen during EndRequest? This should probably be handled at the page level.
如果每个引用都指向特定脚本,我将在每个页面的
Page_Load
中使用ClientScriptManager
。如果您需要根据多个键或每一页中未知的其他因素来计算要链接的脚本,请查看 这个问题。
If each reference points to a specific script, I would use the
ClientScriptManager
inPage_Load
of each page.If you need to calculate the scripts to link in based on more than one key or some other factor not known in each page, then check out answer #2 in this question.