Custom error in asp.net mvc4 - Getting called with every request - asp.net-mvc

I currently have Custom errors setup in a asp.net mvc4 web application in web.config
> <customErrors mode="On" defaultRedirect="~/Errors"> </customErrors>
public class ErrorsController : Controller
{
public ActionResult Index()
{
return Content("Unexpected Error - Please contact Administrator");
}
}
I am not sure why the Action Index gets called on every call even though there is no error
Would help if anybody can clarify this
Thanks

I am not sure why the Action Index gets called on every call even though there is no error
How do you know that there is no error? Maybe the browser is attempting to GET /favicon.ico which you forgot to include in your application and the server is throwing a 404 Not Found exception. Or maybe a missing javascript, css or image? Of course that's only one of the gazillions possible reasons why your Error action might be called.
Once inside the Error action you could always inspect the value of the Request.Url.AbsoluteUri to know more about the exact request sent by the client.

It could be your RouteConfig. If you have a specific route for the error that is being matched before the others than you would keep getting the error.

Related

MVC HandleError filter didn't catch an exception

I've an MVC 3 web app in which I'm using "HandleError" Action Filter for exception handling. I've this action filter implemented as follows:
[HandleError]
public class BaseController : Controller {...}
This is the base class from which all of my controllers are derived. In my web.config I've and there's an Error.cshtml in my Shared folder (.cshtml because I use Razor). Everything has been working fine and I get a fine exception handling (formatted by my function)
Recently, somehow I got and "unhandled exception (YSOD)" and because of "customErrors" I got the default ASP.Net error message which didn't have any info about the actual exception. This happened in an AJAX post back. However, I'm unable to reproduce it.
Is it possible for any sort of errors to escape this action filter?
Is it possible for any sort of errors to escape this action filter?
HandleError filter doesn't catch all the exceptions fired in an application. It can capture exceptions that are fired inside actions, action filters.. simply inside the MVC context. Also it doesn't capture HTTP exceptions having status code other than 500. Relying only on HandleError filter in an MVC application is a bad idea.
You should still rely on the Application_Error event to do some logging and customErrors section to display a custom error page for the exceptions that are not captured by HandleError.
I've written a blog post on this subject that may help you.

ASP.NET MVC Json 404 Response

Similar questions have been asked over and over but for some reason none of the things I have tried have worked. I have an ajax application and when the user request an invalid url I would like to return a JsonResult that looks something like this:
[ error: true, status: 404, message: 'The requested page could not be found... or some other message... ']
I don't want the user to just be redirected to the error page defined in the web.config file as that would take them out of the ajax application.
I have tried the following things:
Custom HandleErrorAttribute - Turns out these only handle 500 errors due to exceptions thrown by my code
Custom FilterAttribute that extends FilterAttribute and implements IExceptionFilter - Same issue as before
Override HandleUnknownAction in the Base Controller - Couldn't figure out how to return a JsonResult from the method
Added a catch all route - My other routes are being used before the catch all route is found
Any thoughts would be appreciate.
•Override HandleUnknownAction in the Base Controller - Couldn't figure out how to return a JsonResult from the method
new JsonResult()
{
Data = your_404_data,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
}.ExecuteResult(ControllerContext);
Updated to include the JsonRequestBehavior - which you will need.
For requests which don't match an existing controller or resource you have two choices - to ditch the standard catch-all route "{controller}/{action}/{id}" and replace it with one that sends the request to a fixed controller that returns this 404-like response that you want.
Or use standard Asp.Net error handling to redirect to a route that will do the same thing. Personally I prefer this solution because it means that you don't have to code loads of routes into your global.
You could give https://github.com/Buildstarted/Errlusion a whirl and create whatever handling you want for a 404. You can probably return a special ajax message if it's an ajax request or return html if it's a standard web browser request if you'd like.

How can I make an error page appear in my MVC application?

Currently I am getting error pages like this:
Server Error in '/' Application.
The partial view 'obj' was not found or no view engine supports the searched locations. The following locations were searched:
Is there a way that I can just return a plain error page to my users when my code has a problem?
You can define an error page in your web.config
http://www.aspdev.org/articles/web.config/
You should add [HandleError] attribute on top of your controller class. In your web.config add or change <customErrors> to <customErrors mode="on" />.
Also, here is a great article about different filters in MVC. One of the attributes covered is HandleError and it shows how to show your users plain text error messages.
http://blogs.msdn.com/b/gduthie/archive/2011/03/17/get-to-know-action-filters-in-asp-net-mvc-3-using-handleerror.aspx
Regards,
Huske
Following links will give you valuable insight on using custom error pages in asp.net mvc
ASP.NET MVC HandleError
ASP.NET MVC 404 Error Handling
1.You can use OnError method in global.asax
2.You can use ErrorHandler attribute and put it on controller or action.
3.You can use GlobalFilters to add error handling to all controllers. This is recommended way and alternative to global.asax
4.You can configure error handling in web.config.

How to redirect to error page in view in MS ASP.NET MVC?

In Controller, RedirectToAction("Error") can redirect to error page. How to write code in view code to allow the page redirected to error.aspx view?
You shouldn't need to handle reporting of errors inside MVC actions, and hard coding error behaviour makes finding a fixing issues harder than it needs to be.
Instead use the HandleError attribute and throw a regular exception:
[HandleError]
public class ThingController : Controller
{
public ActionResult DoStuff()
{
...
// uh-oh! throw exception
throw new WhateverException("message");
}
}
This will allow you to use the customErrors config flag to change your application's behaviour:
<customErrors mode="RemoteOnly" defaultRedirect="~/System/Error" />
Then locally you'll get an ugly but detailed yellow screen of death, plus debug will break on the thrown exception by default.
Remote users will get redirected to your SystemController.Error where you can have a nice user-friendly message and log the error.
This will work for controller actions and views in the same way.
#Jørn is right, but what kinds of errors are you predicting to show up in your view?
If you gave some details on why you're thinking about this, we might be able to suggest some better alternatives instead of simply saying "don't do this."

ASP.net MVC [HandleError] not catching exceptions

In two different application, one a custom the other the sample MVC application you get with a new VS2008 MVC project, [HandleError] is not catching exceptions.
In the sample application I have:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
throw new Exception();
return View();
}
public ActionResult About()
{
return View();
}
}
which is just the default controller with an exception being thrown for testing.
But it doesn't work. Instead of going to the default error.aspx page it shows the debug information in the browser.
The problem first cropped up in a custom application I'm working on which led me to test it with the sample application. Thinking it had something to do with changes I made in the custom application, I left the sample application completely unchanged with the exception (yuck) of the throw in the index method.
I'm stumped. What am I missing?
In Web.config, change customErrors:
<system.web>
<customErrors mode="On">
</customErrors>
If mode is either Off or RemoteOnly, then you will see the yellow screen of death instead of the custom error page. The reasoning is that developers usually want the more detailed information on the yellow screen of death.
Important: Be careful that your error page itself does not have an error on it!
If it does you'll end up with that ASP.NET custom error page and end up going round in circles and tearing your hair out. Just strip everything out of the page that could possibly cause an error and test it.
Also with respect to 'customErrors' being ON or OFF there are several contributing factors to whether or not the friendly error page (your Errors.aspx) page will be shown or not.
See this blog (except below)
HttpContext.IsCustomErrorEnabled - looks at three different sources
The web.config's <deployment> section's retail property. This is a
useful property to set when deploying
your application to a production
server. This overrides any other
settings for custom errors.
The web.config's <customErrors> section's mode property. This setting
indicates whether custom errors are
enabled at all, and if so whether they
are enabled only for remote requests.
The HttpRequest object's IsLocal property. If custom errors are enabled
only for remote requests, you need to
know whether the request is from a
remote computer.
The idea here is that you can have 'customErrors' turned OFF during development - when you do want to see the errors, and then enable it for production only.
This MSDN article discusses the attribute further.
Another reason for this problem may be ,
In Template MVC Application (generated by VS2008 / VS2008 Express) , Error.aspx (generated by VS) uses Master Page.
If Master Page access any ViewData it will throw null reference Exception , then the error.aspx won't be shown.
Use this Simple code as your Error.aspx , it will solve the problem, (along with CustomErrors=On )
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>
<%= Model.Exception.Message %>
I have struggled with this as well and I believe I understand the problem now.
In short the requirements for having [HandleError] work as expected are:
You must enable custom errors in web.config AND you must also specify where your error view is in the <customErrors> tag.
Example:
<customErrors mode="On" defaultRedirect="Error" />
Leaving off the defaultRedirect="Error" part will instead yield a 500 error in the browser--NOT the ASP.NET error page (YSOD).
Also you do not have to be in Release mode. I tested this with a Debug build and it worked fine.
My environment was Visual Studio 2010 using .NET 4 and the standard, "ASP.NET MVC 2 Web Application" project template.
What confused me was the MSDN documentation for the HandleErrorAttribute Class. It doesn't explicitly say you must turn on custom errors in web.config. And I assumed all I needed was the [Handle Error] attribute.
There is some silly situation which once happened with me, so might be helpfull for someone.
Be sure that you've added <customErrors mode="On" /> to the correct web.config file.
Sometimes (especially, when you work with something like Resharper, and open your files with typing their name, but not via Solution Explorer), you can simply open a web.config either from Views folder or even from another project.
Watch out: in my case I was trying to get the HandleError attribute to catch an exception thrown inside the Controllers constructor! Of course it won't catch it. The HandleError attribute only catches exceptions thrown inside Controller actions. It's right there in the MSDN page (should've paid more attention to that):
Represents an attribute that is used to handle an exception that is
thrown by an action method.
Another thing that was happening is that the Controller's OnException(ExceptionContext exceptionContext) overridden method was never being called. Again: of course it would not be called since I was throwing an exception inside the Controller's constructor.
I spent 1 hour trying to figure this out. :o) Hope it helps the next soul...
As a hint: remember that the HandleError attribute only catches 500 errors. For the other ones you should declare the <customErrors> section in Web.config:
<customErrors mode="On">
<error statusCode="403" redirect="~/403" />
<error statusCode="404" redirect="~/404" />
</customErrors>

Resources