views:

49

answers:

1

Like many people using ASP.NET MVC, I've implemented my own custom 404 error handling scheme using an approach similar to the one described here: http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/2577095#2577095

(I actually discovered that post after implementing my own solution, but what I came up with is virtually identical.)

However, I ran into one issue I'm not sure how to properly handle. Here's what my 404 action in my ErrorController class looks like:

    public ActionResult NotFound(string url)
    {
        url = (url ?? "");

        if (Request.Url.OriginalString.Contains(url) &&
            Request.Url.OriginalString != url)
        {
            url = Request.Url.OriginalString;
        }

        url = new Uri(url).AbsolutePath;

        // Check URL to prevent 'retry loop'
        if (url != "/Error/NotFound")
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;

            // Log 404 error just in case something important really is
            // missing from the web site...
            Elmah.ErrorSignal.FromCurrentContext().Raise(
                new HttpException(Response.StatusCode,
                    String.Format("Resource not found: {0}", url)));
        }

        return View();
    }

The part that's different from the answer in the other StackOverflow question I referenced above is how the 'retry loop' is prevented. In other other answer, the code that prevents the retry loop simply sets properties on a ViewModel, which doesn't seem to actually prevent the loop. Since the action is sending back a response code of 404, then accessing the action directly (by typing "/Error/NotFound" in the browser) causes an infinite loop.

So here's my question: Did I miss another, more obvious way to handle the retry loop issue, or is my approach a decent way to do this?

+1  A: 

you can handel erros by enabling the customErrors mode in the web.config file and set it to redirect errors to your controller when any errors occurs.

see an example here

Manaf Abu.Rous
Actually, using web.config in ASP.NET MVC to handle 404 errors isn't recommended because ASP.NET returns a 302/Redirect status code in that case (to redirect the user to your error page) rather than a 404.
Bart McDonough