asp.net mvc errorhandler not showing custom error page - asp.net

I am trying to follow the examples in this link and this one but instead of showing the error page I get an HTTP 500 Internal server error.
I have the <customErrors mode="On" /> set in the webconfig. I have even tried applying the [HandleError] filter to the controller class. I tried without as well. The Error.aspx is present in /Views/Shared/ as well so it couldn't be a case of no file found.
I threw a DivideByZero exception in my controller's action method. I want to follow that example so that I can specify a separate error page for all the actions that need them.
I am using the aspx view engine in a blank project that I created. That should not be the reason for it right?. I am also using a master page for this. Anything that I could be missing?
Thanks
Edit-Added Code
I added this code to a new project and made the web.config entry <customErrors mode="On" />
[HandleError]
public class HomeController : Controller
{
//
// GET: /Home/
[HandleError]
public ActionResult Index()
{
throw new DivideByZeroException();
return View();
}
}
It didnt work! Then I commented that DivideByZeroException and in the aspx view just added and invalid Model.Property. In both instances I got the Internal server error. I have done everything there is to be done as per documentation. I see a lot of other people having the same problem and not being able to solve it too. Is this a bug in MVC 3?

I think I have figured out what really was the problem. My main Home page index was in a master page. I added the same master page to the default error page that comes out of the box with Visual Studio and it worked for me.
The documentation needs to point out more clearly this important requirement,... if it indeed is one.
Another amazing revelation is that you don't need to decorate your controller classes with the [HandleError] attribute. It works without that as well for the default Error view. You may provide that attribute if you want a specific custom view for your action or controller.
Like so:
[HandleError(View = "CustomError")]
...where CustomError.aspx is just another plain aspx view page in either the shared folder for the View or in the View-Controller folder itself.
Has anyone got this working without putting the error pages in a master page, where the main calling page that throws the error is in a master page?

The HandleError filter doesn't catch all the errors. It doesn't catch exceptions that are raised outside controller actions/action filters. Also, it doesn't catch HTTP exceptions having status code other than 500.
So you have to make sure where the exception is getting thrown and you should not rely only on the HandleError to return the custom error page but you also have to set a custom error page in the customErrors section as well.
<customErrors defaultRedirect="error.htm" mode="On"
redirectMode="ResponseRewrite" />

Make sure you have activated custom errors in your web.config:
<customErrors mode="On" />
Also make sure that the ~/Views/Shared/Error.aspx template is present because this is what will be rendered in case of error.

Related

How does error page shown in default internet application ASP.NET MVC

I'm using the default internet application in ASP.NET MVC 3. When an error occurred in the application it automatically redirects to the default error page that is already available in the shared folder inside views.
I'm trying to figure out how does it happening? because i'm not seeing any settings in web.config or Global.asax that forces the application redirect to error page when an error occurred.
It will be in the web.config, it looks like:
<system.web>
<customErrors mode="Off" />
</system.web>
MVC has a default exception filter (HandleError) which provides built-in error handling for you.
It is usually caused by global Action Filter that is registered by default in your global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
Keep in mind though, that by default, the filter will NOT invoke itself if <customErrors mode="Off" /> in your Web.config.
Please note that the HandleError filter does not use redirection, it simply replaces the original ActionResult of the requested Action with it's own ViewResult that uses the Error.cshtml view (unless otherwise specified).
See http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/HandleErrorAttribute.cs

Set specific error pages

In my MVC project i set a Default error page in the web.config
<customErrors defaultRedirect="~/Error/Index" mode="RemoteOnly">
</customErrors>
till now all is fine, in any exception thrown the user get the default error page.
Now i want to add another error page that in specific exception will load instead of the default error page that set in the web.config.
I had an idea: maybe in a new class that inherit "ActionFilterAttribute" and implement "IExceptionFilter", i will in any exception thrown from an action if the type of the exception is my specific case, in this case i need to change the redirect route that set in the web.config as default, but how can i do it? or maybe someone have an another idea?
You don't need to change anything in the web.config. The customErrors in the catches only the exceptions you didn't catch in yours ActionFilters and Controllers.
Good plan Boss!
And read this SO Answer about how I do it, etc. It might help :)
You can specify what views are rendered for a given exception with the HandleErrorAttribute filter

HttpHandler for 404 error stopped working after 4.0 upgrade

I have an HttpHandler which takes care of 404 errors, which I implemented years ago as a way of doing url routing. If the request maps to a valid page, it redirects to that page. Otherwise, it returns a 404. (I know I should start using the new routing feature of asp.net 4.0, but that will take some time. I need to get this working asap.)
In IIS6, I have mapped the 404 error to "/404.ashx". In the web.config, custom errors are set up like so:
<customErrors mode="On" defaultRedirect="error.aspx">
<error statusCode="404" redirect="/404.ashx"/>
</customErrors>
and the http handler:
<httpHandlers>
<add verb="GET" path="404.ashx" type="myNamespace.PageNotFoundHandler,myAssemblyName"/>
</httpHandlers>
This has been working for years - it stopped working as soon as I changed the site to use asp.net 4.0. Everything was recompiled for 4.0, and there were no code changes.
Now, when I hit one of these urls that used to work, I get a blank page with a 404 error code. If I remove the IIS 404 error mapping, I get a regular old 404 page. It seems that the httphandler is not being called.
I have other http handler which are working fine.
I have set the EnableExtensionlessUrls item in the registry to 0, as suggested here and other places.
I figure there must be some configuration setting I missed or something like that. Naturally, this is a problem only on my production server, so I can't run it in the debugger to see what is happening. If nothing easy comes up, I will insert some extra logging in my system to help track it down.
Any ideas on what I else can check?
You might check to see if it's the Verb attribute, maybe it should be POST or *?
Another quick fix would be to add code to your Application_Error event handler in your global class like so.
for (Ex = Server.GetLastError(); Ex != null; Ex = Ex.InnerException)
{
if (Ex is HttpException && ((HttpException)Ex).GetHttpCode() == 404 && Context != null)
{
Context.Server.Transfer("~/404.ashx");
return;
}
}
This would remove the need for any configuration settings inside of your web config, but it might behave somewhat differently than what you currently use as it would take on the page identity of the currently requested page/file instead of passing along the path in a query string as the normal IIS 404 custom error page is handled.
Changing from the default app pool to the classic one fixed it for me.

ASP.NET CustomErrors not firing when exceptions occur in global.asax or in web.config

I have ASP.NET set up to use the CustomErrors functionality:
<customErrors mode="On" defaultRedirect="~/ErrorPages/500.aspx" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="~/ErrorPages/404.aspx" />
<error statusCode="500" redirect="~/ErrorPages/500.aspx" />
</customErrors>
Everything works nice, and the relevant error pages are shown when appropriate.
Except in the following two cases:
1) When there is an exception thrown in global.asax:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
throw new ApplicationException("Exception in Application_Start()");
}
}
2) When there is a syntax error in web.config
In both cases, I don't see my pretty 500.aspx page. Instead, I see the standard ASP.NET yellow screen of death, with the following message:
Server Error in '/MvcErrorHandling' Application.
Runtime Error
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed.
How can I get ASP.NET or IIS to show a custom error page (a pretty one, instead of the YSOD) in the above two scenarios?
Thanks in advance for any input :)
The problem is that those specific errors are happening before ASP.NET can load things up, and your "500 internal server error" page is an .aspx page that requires ASP.NET to load.
The simplest option would be to make your 500 page an HTML page, but that would mean you can't do simple error logging, etc from there.
This may still not help the web.config scenario as if IIS can't process the web.config, there's no guarantee that it would read your error section.
Another option would be to tell IIS to serve a static html page on 500 errors.
Finally you could try catching errors in the Application_Error event in the web.config - this would at least allow you to process the error, even if the page you try to display can't load up.
Edit to add
If you're running IIS 7 in integrated mode, you need to do one more thing if you're setting the response code of your error page to 500:
Response.TrySkipIisCustomErrors = true;
However, note that the following conditions will stop any custom 500 error page from displaying, resulting in the YSOD:
Errors in the web.config or certain handlers in the web.config that fire before the rest of the pipeline (i.e. the bulk of the original answer)
Errors in the error page.

respond with 404 error from asp.net page codebehind

I have a scenario in which I'm serving a file from codebehind.
which file, depends on request. in some cases there will be no file to serve and I want to return 404 to the browser.
how can I do that from codebehind? is this the correct course of action to show user there's no file available?
you can use the Response.StatusCode property to return a 404:
Page.Response.StatusCode = 404
As for the question of whether it's the "correct thing to do" I'd say it depends how the Page is going to be accessed. If you're going to access it programmatically then yes I'd go with the 404. If however it is going to be a user facing system, then I'd go with a custom page of some sort. Programs like codes and humans like more understandable things :-)
throw new HttpException(404, "File not found");
I'd be more inclined to redirect them to a custom error page that clearly indicates that the file cannot be found, in the style of the rest of your web application.
You can specify how to handle certain errors in web.config
<customErrors mode="On">
<error statusCode="404" redirect="FileNotFound.aspx"/>
</customErrors>

Resources