在 MVC 中,我想 return 查看 404 url,而不是重定向!怎么做?

In MVC I want to return view for 404 url, not redirect! How to do it?

我能想到的两个解决方案是:

  1. 不知何故专用一个控制器来接收所有 404 请求(现在不知道怎么做)

  2. 在Global.asax Application_Error中以某种方式通过控制器渲染视图并将结果写入Response(不知道该怎么做)。

我更喜欢第一个选项。

找到答案(2.解决方案)! :)

为此,您应该关闭 web.config 中的自定义错误:

<customErrors mode="Off">

void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();

        if (ex is HttpException)
        {
            var defaultController = new Controllers.ErrorController();
            defaultController.ControllerContext = new ControllerContext(this.Request.RequestContext,
                defaultController
            );
            var res = defaultController.NotFound();
            res.ExecuteResult(defaultController.ControllerContext);
            Server.ClearError();
            Response.TrySkipIisCustomErrors = true;
        }
    }