Question

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.

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top