Trying to access the HttpContext.Current
in a method call back so can I modify a Session
variable, however I receive the exception that HttpContext.Current
is null
. The callback method is fired asynchronously, when the _anAgent
object triggers it.
I'm still unsure of the solution to this after viewing similar questions on SO.
A simplified version of my code looks like so:
public partial class Index : System.Web.UI.Page
protected void Page_Load()
{
// aCallback is an Action<string>, triggered when a callback is received
_anAgent = new WorkAgent(...,
aCallback: Callback);
...
HttpContext.Current.Session["str_var"] = _someStrVariable;
}
protected void SendData() // Called on button click
{
...
var some_str_variable = HttpContext.Current.Session["str_var"];
// The agent sends a message to another server and waits for a call back
// which triggers a method, asynchronously.
_anAgent.DispatchMessage(some_str_variable, some_string_event)
}
// This method is triggered by the _webAgent
protected void Callback(string aStr)
{
// ** This culprit throws the null exception **
HttpContext.Current.Session["str_var"] = aStr;
}
[WebMethod(EnableSession = true)]
public static string GetSessionVar()
{
return HttpContext.Current.Session["str_var"]
}
}
Not sure if necessary but my WorkAgent
class looks like so:
public class WorkAgent
{
public Action<string> OnCallbackReceived { get; private set; }
public WorkAgent(...,
Action<string> aCallback = null)
{
...
OnCallbackReceived = aCallback;
}
...
// This method is triggered when a response is received from another server
public BackendReceived(...)
{
...
OnCallbackReceived(some_string);
}
}
What happens in the code:
Clicking a button calls the SendData()
method, inside this the _webAgent
dispatches a message to another server and waits for reply (in the mean time the user can still interact with this page and refer to the same SessionID
). Once received it calls the BackendReceived()
method which, back in the .aspx.cs page calls the Callback()
method.
Question:
When the WorkAgent
triggers the Callback()
method it tries to access HttpContext.Current
which is null
. Why is that the case when if I continue on, ignoring the exception, I can still obtain the same SessionID
and the Session
variable using the ajax returned GetSessionVar()
method.
Should I be enabling the aspNetCompatibilityEnabled setting?
Should I be creating some sort of asynchronous module handler?
Is this related to Integrated/Classic mode?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…