Can HttpContext.Current be null

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 ?
 
B

bruce barker

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)
 
M

Madhur

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
 
J

Jeff Winn

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top