Other errors find my Error.cshtml, why doesn't 404 error find Error.cshtml?

不羁的心 提交于 2020-01-03 08:06:31

问题


I am tackling ASP.NET, MVC 3, web development, for the first time, all at the same time. Please bear with me, as I know this subject has been discussed heavily from different angles. I still have not found the answer to my specific question: Why doesn't my application find my Error.cshtml file when a 404 occurs, when it finds it just fine with other errors?

(Environment: Win 7 64bit, IIS7, SQL 2008 Express, VS2010, ASP.NET 4, MVC3, EF v4)

I have a controller, WorkerController.cs, that correctly reads and writes from the database. If I change the database name without updating my DbContext, it gives me an error. When I change web.config to always show custom errors, shows me the /Views/Shared/Error.cshtml file.

I do not have a FooController.cs file. If I go to /Foo, I get a 404 error, as expected. It tells me it cannot find the resource /Foo.

When I set customErrors mode="On" and make an http request to /Foo, I get a 404 error saying that /Error.cshtml cannot be found.

I am searching for and reading the posts that discuss the various methods of handling errors with designated controllers, but I really want to know what I'm missing. Why does it find /Error.cshtml for other errors, but not the 404 error?


回答1:


Other than setting customErrors="On", have you defined a specific redirect for 404 errors?

If you have, say, an ErrorController setup your web.config, for instance, like:

<customErrors mode="On" defaultRedirect="/error/Problem">
    <error statusCode="404" redirect="error/FileNotFound"/>
</customErrors>

Or of you'd prefer static html pages for your errors:

<customErrors mode="On" defaultRedirect="Problem.html">
  <error statusCode="404" redirect="FileNotFound.html"/>
</customErrors>

You might want to take a look at this other question for some more information: ASP.NET MVC HandleError.

For improved error handling in MVC, though, you could also take a look at ELMAH (Error Logging Modules and Handlers):

  • You can (should)! get ELMAH as a NuGet package; the installer will do most of the setup for you
  • Take a look at Scott Hanselman's "introductory" post
  • Check this question/ansers on how to use it with ASP.NET MVC: How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?


来源:https://stackoverflow.com/questions/5240066/other-errors-find-my-error-cshtml-why-doesnt-404-error-find-error-cshtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!