Search code examples
.netasp.netasp.net-mvc-2httpcontext

Scope of HttpContext.Current.Items in ASP.NET MVC 2


Hi Inside an action, I have set the HttpContext.Current.Items.Add(...). Now i am redirecting to another action in the same controller. I am not able to get the current HttpContext.

Is this not possible. is there a workaround for this problem instead of using temp data.


Solution

  • The HttpContext is available only during the current HTTP request. If you reditect to another action that's another HTTP request sent by the browser with another HttpContext. If you want to persist data between requests you could either use TempData (available only for 1 redirect) or Session. Under the covers TempData uses the session as storage but it is automatically evicted by the framework after the redirect.

    Example with TempData:

    public ActionResult A()
    {
        TempData["foo"] = "bar";
        return RedirectToAction("B");
    }
    
    public ActionResult B()
    {
        // TempData["foo"] will be available here
        // if this action is called after redirecting
        // from A
        var bar = TempData["foo"] as string;
    
        // TempData["foo"] will no longer be available in C
        return RedirectToAction("C");
    }
    

    Example with Session:

    public ActionResult A()
    {
        Session["foo"] = "bar";
        return RedirectToAction("B");
    }
    
    public ActionResult B()
    {
        var bar = Session["foo"] as string;
        // Session["foo"] will still be available in C
        return RedirectToAction("C");
    }