开发者

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

开发者 https://www.devze.com 2023-02-15 11:04 出处:网络
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 discus开发者_如何转开发sed heavily from different angles.

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 discus开发者_如何转开发sed 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?


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?
0

精彩评论

暂无评论...
验证码 换一张
取 消