c# - 为什么 HttpContext.Current 为空?

标签 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();

  }

并在 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 为空?

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

最佳答案

显然 HttpContext.Current 不是 null 只有当您在处理传入请求的线程中访问它时。这就是“当我在页面的另一类中使用此代码时”它起作用的原因。

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

总的来说,不要使用 Application["Setting"] 来存储全局内容,因为它们不像您发现的那样是全局的。

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

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

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

代替 HttpContext.Current

关于c# - 为什么 HttpContext.Current 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19509672/

相关文章:

c# - 如何使用 MAPI 获取 Outlook 联系人组?

asp.net - 以编程方式从同一池中的 ASP.NET 应用程序回收池

c# - Microsoft.Web.Administration(用于 IIS7 自动化)在 VS 2010 中不起作用

c# - CSS:第一个选择器

c# - 使用网络服务将文档上传到 Sharepoint 2013 Online

html - 嵌入在 aspx 文件中的 @font-face 不起作用

c# - Visual Web Developer 2010 Express - 创建面向 .NET 2.0 的 ASP.NET 网站

c# - MvcHtmlString 和 HtmlString 似乎对简单字符串的包装毫无用处?

php - IIS - Mysql 性能问题

asp.net - 我们可以使用 IIS 而不是 Visual Studio 开发服务器运行 Selenium WebDriver 测试用例吗