如何使用RedirectToAction方法将对象作为隐藏参数传递?

8
我已经这样做了。
public ActionResult GetInfo(SomeModel entity)
{
     ----
     return RedirectToAction("NewAction", "NewController", new System.Web.Routing.RouteValueDictionary(entity));
}

被调用的动作

public ActionResult NewAction(SomeModel smodel)
{
     -------
     -------
}

这个功能目前可以正常使用,但是我发现所有发布的参数值都能在浏览器地址栏中看到,我该如何隐藏这些查询字符串参数值。

http://localhost:51545/NewController/NewAction?SurveyID=13&CatID=1&PrimaryLang=1&SurveryName=Test%20Survery&EnableMultiLang=False&IsActive=False

任何帮助都将不胜感激。

2个回答

13

针对您的情况,不要使用RouteValueDictionary从查询字符串中传递模型,而是尝试使用TempData(因为当我们使用RedirectToAction时,它会创建一个新的http请求并在url中显示对象路由,因此在url中显示敏感数据并不是一个好方法)。

使用以下方式使用TempData

public ActionResult GetInfo(SomeModel entity)
{
  ----
  TempData["entity"] = entity; //put it inside TempData here
  return RedirectToAction("NewAction", "NewController");
}

public ActionResult NewAction()
{
   SomeModel smodel = new SomeModel();
   if(TempData["entity"] != null){
   smodel = (SomeModel)TempData["entity"];  //retrieve TempData values here
   }
   -------
   -------
}
使用TempData的好处在于它会在一个重定向中保留其值,而且模型将被私密传输到另一个控制器操作。一旦你从TempData中读取数据,其数据将自动被处理,如果你想在读取后保留TempData的值,则使用TempData.keep("entity")

或者,如果您的视图在同一个控制器中,则这是解决问题的简单方法:

public ActionResult GetInfo(SomeModel entity)
{
  ----
  return NewAction(entity);
}

public ActionResult NewAction(SomeModel smodel)
{
   -------
   -------
  return View("NewAction",smodel)
}

正如@Chips_100正确评论的那样,我在这里包含它:第一个解决方案将执行真实重定向(302),这将更新用户浏览器中的URL。第二个解决方案将在保留地址栏中的原始URL的同时给出所需的结果。


那看起来过于复杂了。有没有一种方法可以进行服务器端重定向? - Philip Pittle
@PhilipPittle..这有多复杂..你只需将模型放入tempdata中,然后在所需操作上将tempdata强制转换为模型。其中有什么复杂的? - Kartikeya Khosla
@异常:谢谢,它有效。 @Philip Pittle:如果有更高效的建议,将不胜感激。 - 10K35H 5H4KY4
请记住,对于用户来说,这两种解决方案之间存在微妙的差别。第一种将执行真正的重定向(302),这将更新用户浏览器中的URL。第二种解决方案将在保持地址栏中原始URL的同时提供所需的结果。 - Dennis
@Chips_100... 是的,请仔细查看 newaction 中返回视图时我也指定了视图名称。 - Kartikeya Khosla

0
根据您的问题,可以看出隐藏参数是针对用户会话范围的。
因此,您可以将其存储到控制器的Session属性中:
public ActionResult GetInfo(SomeModel entity)
{
     Session["SomeKey"] = "SomeValue";
     return RedirectToAction("NewAction", "NewController");
}

之后,您可以检索它(另一个控制器也可以在此处工作):

public ActionResult NewAction(SomeModel smodel)
{
     var parameter = Session["SomeKey"] as string;

     // Remove the parameter from session storage
     Session.Remove("SomeKey");

     // Do the stuff using provided parameter value

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接