Why is HttpContext.Current null?
Asked Answered
A

6

68

I have a value that I use in all the application; I set this in 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

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)

   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?

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

Allisonallissa answered 22/10, 2013 at 5:31 Comment(0)
M
122

Clearly HttpContext.Current is not null only 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".

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.

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

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 HttpContext or Application["Settings"], as that violates the principles of isolation and decoupling.

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

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

instead of HttpContext.Current.

Morbid answered 22/10, 2013 at 7:29 Comment(6)
Also, have in mind that when using the keywords async/await, lines that follow an await are not neccessarily the same thread that handles the incoming request. Reference HttpContext.Current before your first await to be sure to avoid a NullReferenceException (I have sen functions where it works, other where it doesn't, so being consistent is key)Boxwood
@Lex Li But won't storing Session in a Singleton class have all Users to share same sessionRage
Is there any solution Lex? I'd like to access current user in a class library.Satirical
@Lex Li what is your suggestion?Cotten
@Lex Li Be more to the point. You use unnecessarily colorful language and it's obscuring your answer.Henchman
@Lex Li. How u solve this when u have a component that register user actions across multiple module and u want a single Id to record this information and have a trace? Asuming of coruse we have controllers and threads. RegardsCohabit
C
7

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

Corrianne answered 22/10, 2013 at 5:40 Comment(0)
D
6

try to implement Application_AuthenticateRequest instead of 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.Current object yet).

hope that helps.

Dunagan answered 22/10, 2013 at 5:34 Comment(4)
Thanks, but when i use this code in another class i get value, but in a this class HttpContext.Current is null.Allisonallissa
as i said, it all is being called from Application_Start. move it under Application_AuthenticateRequest in global.asax and it will work!Dunagan
'Object reference not set to an instance of an object.' for HttpContext.CurrentAllisonallissa
let us continue this discussion in chatDunagan
E
2

If you are using an asp.net webforms application, try to add this line in your web.config, it might work for you:

  <appSettings>
   <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
Enlarger answered 22/7, 2022 at 11:10 Comment(0)
W
1

If this is WCF service you can add following in your web.config.

<configuration>
    <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    </system.serviceModel>
</configuration>

A Boolean value indicating whether the ASP.NET compatibility mode has been turned on for the current application. The default is false.

When this attribute is set to true, requests to Windows Communication Foundation (WCF) services flow through the ASP.NET HTTP pipeline, and communication over non-HTTP protocols is prohibited.

Wallford answered 9/6, 2022 at 4:9 Comment(0)
O
0

System.Web.Hosting.HostingEnvironment.MapPath("~/File"); You can solve your problem by using.

Orinasal answered 21/11, 2023 at 19:1 Comment(2)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Tobietobin
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewMyrtlemyrvyn

© 2022 - 2024 — McMap. All rights reserved.