Question

This is my first time working with HttpModules. I need to create a "drag and drop" sort of solution into existing ASP.NET applications that will provide common error handling by redirecting the users to a new "ErrorFeedback.aspx" page. So, when an app encounters an exception, the user will be redirected to ErrorFeedback.aspx where they'll be able to provide feedback surrounding the error, if they need to. We have around 300 web apps currently so the "drag and drop" solution that seems most promising is an HttpModule. This ErrorFeedback page will be a new page that will also be added to the solution as well. Eventually these components (the DLL and the custom web page) will wind up in a Nuget package, but for the time being it will need to be manually copied/pasted into the existing solution.

I've heard that doing a redirect within the module is bad practice. What's the best practice for redirecting a user to a specific page whenever OnError in the HttpModule is encountered?

Was it helpful?

Solution

If you only need to redirect you would be best of using web.config custom error pages. But if you also want to do some more things, like logging for example than you need to use HttpModule, something like this:

public class ErrorManagementModule : IHttpModule
{
    public void Dispose() { }

    public void Init(HttpApplication context)
    {
        //handle context exceptions
        context.Error += (sender, e) => HandleError();
        //handle page exceptions
        context.PostMapRequestHandler += (sender, e) => 
            {
                Page page = HttpContext.Current.Handler as Page;
                if (page != null)
                    page.Error += (_sender, _e) => HandleError();
            };
    }

    private void HandleError()
    {
        Exception ex = HttpContext.Current.Server.GetLastError();
        if (ex == null) return;

        LogException(ex);

        HttpException httpEx = ex as HttpException;
        if (httpEx != null && httpEx.GetHttpCode() == 500)
        {
            HttpContext.Current.Response.Redirect("/PrettyErrorPage.aspx", true);
        }
    }
}

OTHER TIPS

You can use custom error pages in Web.config, instead of HttpModule. But if you really need to redirect, it's better to use RewitePath method.

And here are some notes in general:

  1. When you use URL rewriting, you should be careful about SEO. Because your original URL would count in SERPs.
  2. ASP.NET routing is also a good mechanism and alternative to what you're trying to do
  3. Why do you say that redirection is bad in HttpModule? Any specific reason?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top