views:

198

answers:

1

I've been looking around for some approaches to using ELMaH with ASP.Net MVC so that I can use the custom error page for all exceptions including 404s.

There is no shortage of questions asking how to get the /Shared/Error.aspx working correctly in ASP.Net MVC - either with or without ELMaH. I haven't had a problem with that task, but I feel as though my solution to using a custom 404 page alongside ELMaH was too simple and I can't shake the feeling that there should be more to it.

After enabling customErrors in Web.Config, I created a new Action in my HomeController:

public ActionResult PageNotFound()
{
    return null;
}

From there I added a new method in my Global.asax file to take advantage of ELMaH's log filtering capabilities and, after letting the exception get logged, redirecting the response back to the aforementioned PageNotFound ActionResult:

    public void errorLog_Filtering(object sender, ExceptionFilterEventArgs e)
    {
        if (e.Exception.GetType().Equals(typeof(HttpException)))
        {
            HttpException ex = (HttpException)e.Exception;
            if (ex.GetHttpCode() == 404)
                Response.Redirect("/Home/PageNotFound");
        }
    }

Am I overlooking something that comes with MVC by default (because I'm still finding my way for a lot of things regarding MVC), or overthinking the problem where a simpler solution exists? Appreciate any input.

+1  A: 

I am sure ASP.NET can handle that kind of stuff for you, you don't necessarily have to call anything to redirect to your 404 Action inside your global.asax. See below for an example.

<configuration>
    <system.web>
        <customErrors mode="On">
            <error statusCode="404" redirect="/servererrors/404.aspx" />
        </customErrors>
    </system.web>
</configuration>

http://www.xefteri.com/articles/show.cfm?id=11

Khalid Abuhakmeh
Ok. First of all, that article you've linked to was written in 2002(!) for a target audience of .Net 1.1 webforms developers. However, your answer has made me look at my approach again and, as I suspected, I've over-engineered things. I don't need the errorLog_Filtering event in Global.asax, but I *do* need a reachable ActionResult. Thanks for the input.
Phil.Wheeler
Sorry, the article is pretty old but the configuration aspect of it is still pretty relevant. Little has changed when it comes to asp.net configurations.
Khalid Abuhakmeh