开发者

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

开发者 https://www.devze.com 2023-03-04 22:47 出处:网络
Hi Inside an action, I have set the HttpContext.Current.Items.Add(...开发者_如何学Python). Now i am redirecting to another action in the same controller. I am not able to get the current HttpContext.

Hi Inside an action, I have set the HttpContext.Current.Items.Add(...开发者_如何学Python). 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.


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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消