Can HttpContext.Current be null

  • Thread starter Thread starter Madhur
  • Start date Start date
M

Madhur

Hello

I am delivering an asp.net 2.0 application to my customer. I need to know,
If I need to check for the condition of HttpContext.Current to be null
in my business logic. I have extensively used Cache and Session objects, and
currently I assume HttpContext.Current object to be existent.

Also, since I do not have this check, some of my unit test cases fail
because there is no HttpContext for them.

How do you handle this scenario. ?

Should I include check for existence of HttpContext.Current and may be even
more for Session and Cache objects ?
 
HttpContext is defined by the asp.net request processor. it will be null
if your classes are not referenced from a web request. it will be null
in a unit test, for a control loaded in the designer, or if your code
starts a background thread, it will be null in the new thread.

-- bruce (sqlwork.com)
 
Hi Bruce

Thanks for the info.

Do you have any recommendations on how to go about the unit testing of the
procedures which make use of
HttpContext, session or Cache objects.

Thanks in Advance.

Madhur
 
Like Bruce said earlier, HttpContext.Current can be null - however accessing
the contextual information from an ASP.NET page or user control will most
likely ensure that it never will be null. HttpContext.Current really depends
when it's being accessed to determine if it contains any data.

As for your followup question, just structure your code so it won't rely on
having contextual information available. As long as the context information
is only used from your website you shouldn't have any problems writing unit
tests for your business logic. Also, not requiring the context information
would allow you to reuse the assemblies (assuming you have your business
logic separated from your presentation layer) in other applications by
simply referencing the assembly.

void DoSomething() {
int id = (int)HttpContext.Current.Session["id"];

// Use the id.
}

void DoSomething(int id) {
// Use the id.
}

protected void Page_Load(object sender, EventArgs e) {
this.DoSomething((int)this.Session["id"]);
}

You can see both methods do the exact same thing, one of them just doesn't
rely on context information while the other does.
 
Back
Top