【问题标题】:Pass data between events of HttpApplication in .Net在 .Net 中的 HttpApplication 事件之间传递数据
【发布时间】:2019-10-28 18:00:56
【问题描述】:

我正在寻找一种在 HttpApplication 事件之间传递数据的方法。例如,我的 HTTP 模块中有以下代码:

public void Init(HttpApplication context)
{
    context.BeginRequest += DoFoo;
    context.EndRequest += DoBar;
}

我想在DoFoo 方法中的BeginRequest 事件期间保存一些数据,稍后在DoBar 方法中的EndRequest 事件期间访问它。

据我所知,Session 目前尚不可用。有没有办法在事件之间存储数据,以便它是:

  1. 可用于当前和所有后续活动;
  2. 只能在当前请求的范围内访问。

更新:

是否可以使用 HTTP 模块实例变量来实现这一点?是否存在存储在这些变量中的数据在当前请求之外可以访问的风险?

【问题讨论】:

  • this 有帮助吗?
  • @wazz,谢谢你的链接。在 StackOverflow 上发布我的问题之前,我已经浏览了这个 MSDN 页面。不幸的是,它没有关于在事件之间传递数据的任何信息。
  • 您正在寻找HttpContext.Item
  • @JohnWu,谢谢,这正是我想要的!

标签: asp.net .net


【解决方案1】:

根据 John Wo 在我的问题下的评论,我的问题已通过使用 HttpContext.Items 解决。 This is the link to the article provided by John.

HttpContext.Items使用示例:

public void Init(HttpApplication context)
{
    context.BeginRequest += DoFoo;
    context.EndRequest += DoBar;
}

private void DoFoo(Object sender, EventArgs e)
{
    HttpApplication httpApplication = (HttpApplication)sender;
    httpApplication.Context.Items.Add("MyFlag", true);
}

private void DoBar(Object sender, EventArgs e)
{
    HttpApplication httpApplication = (HttpApplication)sender;
    if(httpApplication.Context.Items.Contains("MyFlag") && (bool)contextItems["MyFlag"] == true)
    {
        //Do stuff...
    }
}

【讨论】:

    【解决方案2】:

    我不确定 Session 何时首次可用,但我可以通过 Global.asax 中的这个鲜为人知的事件访问它,fwiw:

    // This event is executed for every page request
    // and is run before the PreInit event.
    protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        Session["ok"] = "OK";
    }
    

    【讨论】:

    • 问题是我需要在 HTTP 模块中的事件之间传递数据,并且在尝试访问那里的 Session 时在运行时遇到错误。我相信这是因为 HTTP 模块在页面返回到浏览器之前运行,此时 Session 尚未初始化或处于只读状态。
    猜你喜欢
    • 2014-02-23
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 2016-08-24
    • 2023-03-27
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多