views:

299

answers:

2

I have an item that I store in the HttpContext:

HttpContext.Current.Items["myItem"] = "123";

I can access this no problem from any of a page's methods. For example:

protected override void OnLoad(EventArgs e)
{
    string l_myItemVal = HttpContext.Current.Items["myItem"] as string; // "123"
}

This works fine.

However, when calling one of the page's web methods via AJAX, this fails:

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string MyWebMethod()
{
    string l_myItemVal = HttpContext.Current.Items["myItem"] as string; // NULL
}

Is the HttpContext of an asynchronous call different from the HttpContext for the page?

A: 

Maybe you need to enable session state to make this work:

[System.Web.Services.WebMethod(true)]
Ray
@Ray: -1. Session state has nothing to do with `HttpContext.Items`
John Saunders
that is true - I suggested it as an experiment to see if it would allow access to HttpContent - wouldn't be the first time that we saw unexpected/unintended consequences. I read his problem to be accessing the HttpContext itself. Your answer (items relevant to one request only) is probably correct.
Ray
+1  A: 

HttpContext.Items only holds items during a single request. Your AJAX request is a second request, and has it's own Items property.

John Saunders