【问题标题】:Error page (response) is not shown when error occurs - customErrors is ON发生错误时不显示错误页面(响应) - customErrors 为 ON
【发布时间】:2018-03-15 02:51:45
【问题描述】:

我有一个标准的 ASP.NET MVC 应用程序。这里我想将所有错误重定向到自定义错误页面。

我已尝试根据我通常做的 + 可以 Google 进行设置,但我仍然没有收到错误。

我有以下 web.config

<system.web>
    <customErrors mode="On" defaultRedirect="~/Error/Index">
      <error redirect="~/Error/NotFound" statusCode="404" />
      <error redirect="~/Error/Index" statusCode="500" />

    </customErrors>
    <!-- More stuff :-) -->
  </system.web>
  <system.webServer>

这是我的错误控制器:

 public class ErrorController : Controller
    {
        public ViewResult Index()
        {
            return View("Error");
        }
        public ViewResult NotFound()
        {
            Response.StatusCode = 404; 
            return View("NotFound");
        }
    }

我有以下FilterConfig

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

但是,当我在索引控制器中创建错误时:

    public ActionResult Index(InvoiceOverviewViewModel vm)
    {
        // used to test error pages :D
        int a = 5;
        int b = 0;
        int res = a / b;
    }

这给出了一个错误,我看到以下内容:

而我在ErrorController 内的Index.cshtml 具有以下视图:

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_VerifyLayout.cshtml";
}

<h1>Danish text that doesn't make any sense here ;-) </h1>

更奇怪的是,我的 404 页面可以正常工作。此页面在 localhost 上完美呈现(不过,not on production)。

有什么想法吗?

【问题讨论】:

    标签: c# asp.net-mvc


    【解决方案1】:

    问题 1:

    虽然我在 ErrorController 中的 Index.cshtml 具有以下内容 查看...

    您的错误视图名为Index,但在ErrorController 中,您尝试返回名称为Error 的不存在视图:

    return View("Error");
    

    ErrorController.Index() 方法更改为:

    public ViewResult Index()
    {
        return View("Index");
    }
    

    或不带参数调用View(),默认为"Index"

    public ViewResult Index()
    {
        return View();
    }
    

    问题 #2:

    filters.Add(new HandleErrorAttribute());

    您实际上应该删除 HandleErrorAttribute 过滤器。此过滤器将处理控制器操作引发的异常,并且它有自己的逻辑来选择结果错误视图,这将阻止显示您的自定义错误页面。特别是,HandleErrorAttribute 使用“~/Views/Shared/Error.cshtml”。这就是您看到的错误视图的来源 - “处理您的请求时发生错误。”

    希望这会有所帮助。以下是一些关于 ASP.NET MVC 中的错误处理的有用资源:

    【讨论】:

      猜你喜欢
      • 2013-02-25
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      相关资源
      最近更新 更多