C# 为什么 HttpContext.Current 为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19509672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:09:26  来源:igfitidea点击:

Why is HttpContext.Current null?

c#asp.netiishttpcontext

提问by ar.gorgin

I have a value that I use in all the application; I set this in application_start

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

  }

and in SmsSchedule

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

I want to get this value in a class.(smsjob)

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

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

but my problem is : HttpContext.Current is null, why is HttpContext.Current null?

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

Edit:When i use this code in another class of a page it works, but in this class I get the error.

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

采纳答案by Lex Li

Clearly HttpContext.Currentis not nullonly if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

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

It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.

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

Overall, don't use Application["Setting"]to store global stuffs, as they are not global as you discovered.

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

If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContextor Application["Settings"], as that violates the principles of isolation and decoupling.

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

Update: Due to the introduction of async/awaitit is more often that such issues happen, so you might consider the following tip,

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

In general, you should only call HttpContext.Currentin only a few scenarios (within an HTTP module for example). In all other cases, you should use

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

instead of HttpContext.Current.

而不是HttpContext.Current.

回答by geevee

try to implement Application_AuthenticateRequestinstead of Application_Start.

尝试实现Application_AuthenticateRequest而不是Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start(which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Currentobject yet).

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

hope that helps.

希望有帮助。

回答by Tasos K.

In IIS7 with integrated mode, Currentis not available in Application_Start. There is a similar thread here.

在具有集成模式的 IIS7 中,CurrentApplication_Start. 有一个类似的线程在这里