【问题标题】:TempData is empty after RedirectToAction in catch block. What could be the reason?在 catch 块中的 RedirectToAction 之后 TempData 为空。可能是什么原因?
【发布时间】:2014-04-22 11:39:36
【问题描述】:

我已经使用 TempData 很长时间了,但我遇到了奇怪的问题。我有基本情况:

[HttpPost]
public ActionResult Create(ProductCreateModel newProduct)
{
    // create and save product to db

    // try upload product to external site
    try { UploadProductToEbay(newProduct); } 
    catch { 
              TempData["error"] = "error";
              return RedirectToAction("Edit", newProduct.Id);
    }
    ...
}

[HttpGet]
public ActionResult Edit(int Id)
{
    var error = TempData["error"]; // at this point temp data collection is empty and have no idea why
    ...
}

当上传失败并执行return RedirectToAction("Edit", newProduct.Id); 行时会出现此问题。丢失临时数据值的原因可能不是很明显?

更新: 当我使用

TempData["error"] = "error";
RedirectToAction(...);

catch 块之外一切正常,临时数据值被传输到Edit 操作。

【问题讨论】:

标签: c# asp.net-mvc tempdata


【解决方案1】:

看来问题出在return RedirectToAction("Edit", newProduct.Id); 语句中。
试试这个说法return RedirectToAction("Edit", new{Id=newProduct.Id});
路由参数是object 类型,您传递int

【讨论】:

  • 这不是问题,重定向工作正常,这不是实际代码,我真的使用 new{Id=newProduct.Id} 但问题是临时数据以某种方式相关。
  • 好的,您正在从 POST 操作重定向到 GET 操作,这可能会造成问题。我不确定。:)
  • 我在更新中写过这个问题,仅当在 catch 块中调用 TempData 值分配和重定向时才会发生问题。否则一切都会按预期进行。
猜你喜欢
  • 2020-03-16
  • 2011-09-29
  • 2021-11-01
  • 1970-01-01
  • 2013-02-16
  • 2021-09-01
  • 2012-01-01
  • 2022-08-18
  • 2015-05-05
相关资源
最近更新 更多