1

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.

Nick Olsen
  • 6,299
  • 11
  • 53
  • 75
  • How can your other routes be used if it's a 404 you are expecting? – Lazarus Mar 02 '12 at 16:55
  • The url /NonExistantController/NonExistantAction/ still matches the stock route /{Controller}/{Action}/{id} so that route is used before the catch all route of {*url} – Nick Olsen Mar 02 '12 at 18:02

1 Answers1

2

•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.

Andras Zoltan
  • 41,961
  • 13
  • 104
  • 160
  • Works great. What about an unknown controller though? – Nick Olsen Mar 02 '12 at 18:42
  • @NickOlsen - have updated my answer; basically either ditch the default route for a 404 catch-all; or use Asp.Net custom error responses to redirect to a controller that returns this response. If it's IIS 7, which I'm sure it is, you can also use IIS custom errors in the web.config to do the same thing. – Andras Zoltan Mar 02 '12 at 21:29