为什么HttpContext.Current为null?

ar.*_*gin 42 c# asp.net iis httpcontext

我有一个在所有应用程序中使用的值; 我在application_start中设置了它

  void Application_Start(object sender, EventArgs e)
  {
    Dictionary<int, IList<string>> Panels = new Dictionary<int, IList<string>>();
    List<clsPanelSetting> setting = clsPanelSettingFactory.GetAll();
    foreach (clsPanelSetting panel in setting)
    {
        Panels.Add(panel.AdminId, new List<string>() { panel.Phone,panel.UserName,panel.Password});
    }
    Application["Setting"] = Panels;

    SmsSchedule we = new SmsSchedule();
    we.Run();

  }
Run Code Online (Sandbox Code Playgroud)

并在SmsSchedule

public class SmsSchedule : ISchedule
{
    public void Run()
    {           
        DateTimeOffset startTime = DateBuilder.FutureDate(2, IntervalUnit.Second);
        IJobDetail job = JobBuilder.Create<SmsJob>()
            .WithIdentity("job1")
            .Build();

        ITrigger trigger = TriggerBuilder.Create()
             .WithIdentity("trigger1")
             .StartAt(startTime)
             .WithSimpleSchedule(x => x.WithIntervalInSeconds(60).RepeatForever())
             .Build();

        ISchedulerFactory sf = new StdSchedulerFactory();
        IScheduler sc = sf.GetScheduler();
        sc.ScheduleJob(job, trigger);

        sc.Start();
    }
}
Run Code Online (Sandbox Code Playgroud)

我想在课堂上获得这个价值.(smsjob)

   public class SmsJob : IJob 
   {  
      public virtual void Execute(IJobExecutionContext context)
      {
          HttpContext.Current.Application["Setting"]; 
      }
   }
Run Code Online (Sandbox Code Playgroud)

但我的问题是:HttpContext.Current为null,为什么HttpContext.Current为null?

编辑: 当我在一个页面的另一个类中使用此代码时它可以工作,但在这个类中我得到错误.

Lex*_* Li 85

显然HttpContext.Current,null不仅是您在处理传入请求的线程中访问它.这就是为什么它"在我在一个页面的另一个类中使用此代码时"工作的原因.

它不能在调度相关类中工作,因为相关代码不是在有效线程上执行,而是后台线程,它没有与之关联的HTTP上下文.

总的来说,不要Application["Setting"]用来存储全局的东西,因为它们并不像你发现的那样是全局的.

如果需要将某些信息传递给业务逻辑层,请将参数作为参数传递给相关方法.不要让你的商业逻辑层访问之类的东西HttpContext或者Application["Settings"]作为违反隔离和去耦的原则.

更新:由于引入async/await它经常发生此类问题,因此您可能会考虑以下提示,

通常,您应该只HttpContext.Current在几个场景中调用(例如在HTTP模块中).在所有其他情况下,您应该使用

而不是HttpContext.Current.

  • 另外,请记住,当使用关键字`async/await`时,`await`后面的行不一定是处理传入请求的相同线程.在第一次`await`之前引用`HttpContext.Current`以确保避免出现`NullReferenceException`(我有函数在哪里工作,其他地方没有,所以保持一致是关键) (12认同)
  • @Lex Li更加重视.你使用不必要的多彩语言,它会模糊你的答案. (3认同)

gee*_*vee 7

尝试实现Application_AuthenticateRequest而不是Application_Start.

这个方法有一个实例HttpContext.Current,不像Application_Start(在应用程序生命周期中很快就会触发,很快就不能保存一个HttpContext.Current对象).

希望有所帮助.


Tas*_* K. 7

在具有集成模式的IIS7中,Current不可用Application_Start.有一个类似的线程在这里.