简体   繁体   中英

Session Access and Async Callbacks

Ok, so I have a bunch of async web service calls that I make on the landing page of my website. I want to set the results of these calls to session so that I can use them later, but I can't because HttpContext.Current is null in the callback. Basically, I want to do something like this:

public ActionResult Something()
{
    GetLoans();              //each of these is async
    GetPartInfo();           //and sets its result to session
    GetOtherAsyncStuff();    //(or at least it needs to)
    //lots of other stuff
    Return View();
}

Where GetLoans() looks like this:

public IAsyncResult GetLoans()
{
    IAsyncResult _ar;
    GetLoansDelegate d_Loans = new GetLoansDelegate(GetLoansAsync);
    _ar = d_Loans.BeginInvoke(parameter1,parameter2, GetLoansCallback, new object()); //new object() is just a placeholder for the real parameters im putting there
    return _ar;
}

Which asynchronously invokes GetLoansAsync , whose callback is GetLoansCallback() , shown here:

private void GetLoansCallback(IAsyncResult ar)
{
    AsyncResult result = (AsyncResult)ar;
    GetLoansDelegate caller = (GetLoansDelegate)result.AsyncDelegate;
    List<Loan> loans = caller.EndInvoke(ar);

    Session["Loans"] = loans;   //this call blows up, since HttpContext.Current is null
}

I can't implement a custom session provider, so I have to stick with what I've got there. So as it stands, I can't set anything to session in my async callback. Is there a way to get around this?

You might take a look at this blog post .

Basically, it says that HttpContext cannot be available upon the work completion (ie in the callback) and it looks like that you will have to move the session operations into the GetLoansAsync method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM