在查询字符串MVC上使用数据

时间:2011-02-07 21:22:56

标签: asp.net-mvc

我正在创建一个像这样的动作的重定向......

  Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));

如何重定向时,Action方法可以使用exception.Message吗?

 public ActionResult MyAction()

2 个答案:

答案 0 :(得分:3)

您需要在Action中使用一个参数来接收查询字符串参数。

return RedirectToAction("Your_Action_Name", new { msg = exception.Message});

你的行动:

public ActionResult Your_Action_Name(string msg)

答案 1 :(得分:0)

重定向时,您只能拥有查询字符串参数。所以:

Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));

和:

public ActionResult MyAction(string message)
{
    ...
}

这就是说,在ASP.NET MVC应用程序中使用Response.Redirect并对网址进行硬编码似乎非常错误。遗憾的是,您没有提供任何有关您尝试执行操作的上下文,因此我不确定是否可以为您提供更好的建议:不要在ASP.NET MVC应用程序中使用Response.Redirect。使用URL帮助程序和操作结果,如:

public ActionResult Foo()
{
    ...
    return RedirectToAction(action, "error", new { message = ex.Message });
}

如果你试图实现一些全局错误处理程序而不是你可能正在使用Application_Error事件(顺便提一下你应该在你的问题中提到这一点),那么你可以在这些行中找到一些东西:

var routeData = new RouteData();
routeData.Values["controller"] = "error";
routeData.Values["action"] = action;
routeData.Values["exception"] = exception;
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
等等等......

相关问题