MVC InvalidOperationException with custom error pages

谁说我不能喝 提交于 2019-11-30 18:34:53

MVC projects by default adds the HandleErrorAttribute in the Global.asax.cs file

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

This filter is executed when an unhandled exception is thrown. It sets the view as Error. Hence MVC runtime tries to render that view. But in your case, there is no such view. So it again throws another exception which is handled by ASP.NET runtime and shows your error page that you have configured in Web.Config file.

You can create your own exception filter and register it.

I ended up taking out the registration of HandleErrorAttribute in Global.asax and just using the <customErrors> section. ELMAH now properly logs errors, and I'm able to specify custom error pages.

Am I missing something?

You can also make sure that the HandleErrorAttribute is not registered by removing it from the global filters, using the Remove method:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Remove(new HandleErrorAttribute());
        /* ... your other filters */
    }
}

For future readers of this post, note that Elmah adds its own HandleErrorAttribute so is also expecting the Error.cshtml view. Note that I also installed the Elmah.MVC NuGet package but that is just used to set it up properly.

Yes, just noticed on nuget.org that Elmah.MVC is responsible for adding the HandleErrorAttribute:

Painless integration of ELMAH functionality into ASP.NET MVC Application. Just drop the package inside your ASP.NET MVC application and access /elmah URL. It will also install global HandleError filter, that guarantees all unhandled errors are logged (even if customError turned "On").

To disable ELMAH's HandleErrorAttribute add the following line to the appSettings section of your Web.Config file:

<!-- language: lang-xml -->
<add key="elmah.mvc.disableHandleErrorFilter" value="true" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!