【问题标题】:Redirect to action in filterContext Result not working ASP.NET MVC重定向到 filterContext 结果中的操作不起作用 ASP.NET MVC
【发布时间】:2020-05-17 14:53:19
【问题描述】:

我试图在我的OnException 方法中重定向到Controller,但页面返回的是空白视图,并且链接不会更改为我重定向到的页面。请指教。

这是代码:

protected override void OnException(ExceptionContext filterContext)
{
  if (filterContext.ExceptionHandled) return;

  if (filterContext.Exception is PolicyInForceException)
  {
    PolicyInForceException pife = filterContext.Exception as PolicyInForceException;
    filterContext.ExceptionHandled = true;
    filterContext.HttpContext.Response.Clear();
    filterContext.HttpContext.Server.ClearError();

    filterContext.Result = View(
      new RouteValueDictionary(
        new { area = "", controller = "quote", action = "Confirmation", id = pife.RequestId }
      )
    );

  }
  else
  {
    base.OnException(filterContext);
  }
}

【问题讨论】:

    标签: asp.net-mvc model-view-controller controller


    【解决方案1】:

    通常,要进行重定向,您希望返回一个 RedirectResult 实例。最简单的方法是调用以下任何Controller 方法而不是View():

    在您的情况下,由于您要重定向到特定操作,因此您可能希望使用 RedirectToAction() 方法:

    filterContext.Result = RedirectToAction(
      "Confirmation", 
      "Quote", 
      new RouteValueDictionary(new { 
        id = pife.RequestId 
      })
    );
    

    也就是说,您也可以使用RedirectToRoute() 与您的原始代码几乎相同:

    filterContext.Result = RedirectToRoute(
      new RouteValueDictionary(new { 
        area = "", 
        controller = "Quote", 
        action = "Confirmation", 
        id = pife.RequestId 
      })
    );
    

    相比之下,在您当前的代码中,您只是为当前操作返回了一个视图,而您构建的 RouteValueDictionary 正在以该视图作为其视图模型返回,这可能就是您为什么要看到一个空白页。

    【讨论】:

    • 非常感谢您的回答!!
    • 我尝试使用 RedirectToAction() 但现在出现服务器错误...
    • @MarisolFloresRivera:您收到的错误信息是什么?
    • 我收到 404 服务器错误。找不到资源。
    • @MarisolFloresRivera:啊,在那种情况下,我假设它正在执行重定向,但最终走错了路线?提供 404 的 URL 是什么样的?假设默认路由约定,我希望它会将您重定向到 /Quote/Confirmation/123(其中 123 是您的 pife.RequestId 值)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多