为什么 HttpContext.Current 为空?

2023-11-24

我有一个在所有应用程序中使用的值;我在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();

  }

并在 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();
    }
}

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

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

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

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


Clearly HttpContext.Current is not null仅当您在处理传入请求的线程中访问它时。这就是为什么“当我在页面的另一个类中使用此代码时”它起作用的原因。

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

总的来说,不要使用Application["Setting"]存储全球性的东西,因为它们并不像您发现的那样是全球性的。

如果您需要将某些信息传递到业务逻辑层,请将其作为参数传递给相关方法。不要让您的业务逻辑层访问诸如HttpContext or Application["Settings"],因为这违反了隔离和解耦的原则。

更新: 由于引入async/await此类问题发生的频率更高,因此您可以考虑以下提示,

一般来说,你应该只调用HttpContext.Current仅在少数情况下(例如在 HTTP 模块内)。在所有其他情况下,您应该使用

  • Page.Context https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.context?view=netframework-4.7.2
  • Controller.HttpContext https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.httpcontext?view=aspnet-mvc-5.2

代替HttpContext.Current.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 HttpContext.Current 为空? 的相关文章

随机推荐