【问题标题】:Custom error pages in different areas in ASP.NET MVC3ASP.NET MVC3 中不同区域的自定义错误页面
【发布时间】:2026-01-31 02:40:01
【问题描述】:

我在我的网站上设置了自定义错误页面,使用

<customErrors mode="RemoteOnly" defaultRedirect="~/Error">
  <error statusCode="500" redirect="~/Error/InternalError"/>
  <error statusCode="404" redirect="~/Error/FileNotFound"/>
  <error statusCode="403" redirect="~/Error/AccessDenied"/>
</customErrors>

但是网站上有另一个区域,供应商,当供应商区域发生错误时,重定向会转到 Suppliers/Error/_。由于我在这里没有任何错误页面,因此该站点似乎挂起从未显示错误页面。如何在无需将错误页面复制到供应商区域的情况下解决此问题?

【问题讨论】:

  • 在 Suppliers 区域的 Views 文件夹中,将 customErrors 添加到 web.config
  • 看看这是否有帮助*.com/questions/5226791/…

标签: c# asp.net-mvc-3 error-handling


【解决方案1】:

据我了解,您使用 MVC 构成的 URL 默认为:

域/控制器/动作/id

如果您有一个“错误”控制器。在您的逻辑中,您测试该请求是否来自需要重定向到“供应商”错误页面的站点用户

 [HandleError]
    public ActionResult Index()
    {
        // Test to see if you need to go to the SuppliersController
        if (this.User.IsInRole("supplier"))
        {
            return Redirect("/Suppliers/Error");
        }
        else
        {
            return View(); // This returns the "Error" View from the shared folder
        }
    }

重定向到供应商控制器上的错误处理操作,该操作将返回正确的视图。

public class SuppliersController : Controller
{
    //
    // GET: /Suppliers/

    public ActionResult Error()
    {
        return View("Error","SomeMasterPage"); // No "Error" view in Suppliers View folder, so it uses the one in shared folder
    }

}

您还可以在供应商错误操作中使用[Authorize] 属性来确保用户已登录。

通过这种方式,您将获得所需的/Suppliers/Error URL,并可以使用 SuppliersController Action 指定所需的视图、模型和主/布局页面。

还可以看看这个对类似问题的非常全面的回复:

Best 404 example I can find for mvc

【讨论】:

    【解决方案2】:

    我想在错误页面之前删除“~”应该可以解决问题,但您需要“\”。

    另一种方法是在 redirect/defaultRedirect 属性中写入完整的 URL。

    【讨论】:

      最近更新 更多