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.

2
  • How can your other routes be used if it's a 404 you are expecting? Commented Mar 2, 2012 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} Commented Mar 2, 2012 at 18:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Works great. What about an unknown controller though?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.