catch 块中的 MVC RedirectToAction

发布于 2024-12-18 04:41:50 字数 751 浏览 6 评论 0原文

如果 try 块中出现问题,我会尝试将操作从一个控制器重定向到另一个控制器。我想要实现的是,如果不同控制器中出现问题,通过将所有错误定向到我的 Homecontroller 中的错误处理 ActionResult 来向用户呈现视图的通用方法。这基本上就是代码的样子:

    try
    {
        Code that may go wrong
    }
    catch (Exception e)
    {
        set the errorcode (integer)

        Logg the error (write a simple textfile)

        RedirectToAction("ErrorHandling", "Home", errorcode);
    }

在 Homecontroller 中,我想生成一个视图,告诉用户出了问题:

    public ActionResult ErrorHandling(int errorcode)
    {
        do something with the errorcode

        return View(different view depending on errorcode);
    }

我的问题是,如果我操纵代码,以便在 catcblock 中的每一步抛出异常,除被忽略的 RedirectToAction 外均已执行。我缺少什么?我对此很陌生,所以希望有一个我找不到的简单答案......

I´m trying to redirect to an action from one controller to another if something in a try-block goes wrong. What I want to achieve is a general way of presenting a view to the user if something goes wrong in different controllers by directing all errors to an errorhandling ActionResult in my Homecontroller. This is basically what the code looks like:

    try
    {
        Code that may go wrong
    }
    catch (Exception e)
    {
        set the errorcode (integer)

        Logg the error (write a simple textfile)

        RedirectToAction("ErrorHandling", "Home", errorcode);
    }

And in the Homecontroller i would like to generate a view, telling the user that something went wrong:

    public ActionResult ErrorHandling(int errorcode)
    {
        do something with the errorcode

        return View(different view depending on errorcode);
    }

My problem is that if i manipulate the code so that an exception is thrown every step in the catcblock is executed except for the RedirectToAction whic is being ignored. What am i missing? I´m kind of new to this, so hopefully there is a simple answer that i haven´t been able to find...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

羞稚 2024-12-25 04:41:50

在您的 catch 块中 try

  return new RedirectToRouteResult(new RouteValueDictionary
    { 
        {"Controller", "Home"}, 
        {"Action", "ErrorHandling"},
        {"errorcode", errorcode}
    });

也许您只是忘记了代码中的 return :

return RedirectToAction("ErrorHandling", "Home", errorcode);

In your catch block try

  return new RedirectToRouteResult(new RouteValueDictionary
    { 
        {"Controller", "Home"}, 
        {"Action", "ErrorHandling"},
        {"errorcode", errorcode}
    });

Maybe you simply forgot the return in your code:

return RedirectToAction("ErrorHandling", "Home", errorcode);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文