如何使用TempData在mvc控制器之间传递对象?

时间:2016-01-10 02:41:19

标签: c# asp.net-mvc

当我的一个控制器中抛出异常时,我会在我的基类中使用OnException捕获它,我想将异常对象传递给我的ErrorController的索引操作以在视图中显示。 / p>

在下面的示例中,我使用的是TempData,它最终会在到达我的ErrorController之前被丢弃。

我知道TempData只会持续到下一个请求,但为什么不能这样做呢?

我也对其他解决方法持开放态度。

测试控制器

with self.assertRaises(mouse16.BadInternalCallException):
    stack.insertn([8, 4, 12], 16)

基本控制器

public class TestController : BaseController
{
    public ActionResult Index()
    {
        throw new Exception("test");
    }
}

2 个答案:

答案 0 :(得分:1)

您应该创建自己的异常过滤器来处理错误

public class CustomExceptionHandlerAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if(filterContext.ExceptionHandled)
            return;

        ConfigureResponse(filterContext);

        filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
        {
            {"controller", Test},
            {"action", Index},
            {"exceptionMessage", filterContext.Exception.Message}
        });

        // log your error
        base.OnException(filterContext);
    }

    private void ConfigureResponse(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.HttpContext.Response.Clear();
        filterContext.HttpContext.Response.StatusCode = 500;

        filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }        
}

然后你应该在你的FilterConfig课程中注册你的过滤器:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CustomExceptionHandlerAttribute());
    }
}

现在,当您的应用程序生成未处理的异常时,将对此ActionFilter进行处理。

你的行动将是:

public ActionResult Test(string exceptionMessage)
{
    return View(exceptionMessage);
}

答案 1 :(得分:0)

您不需要在viewData中保存Exception。当发生一个exseption或错误只是将用户重定向到客户查看像Error并向用户显示错误像这样: 为您的模型设置以下型号:

@model System.Web.Mvc.HandleErrorInfo

现在您可以阅读发生的错误并将其保存在db中并向用户显示消息。

以下链接与您的问题相似:

Link