Search code examples
asp.net-mvcelmahelmah.mvc

Elmah getting stuck in default route?


I added Elmah.MVC to my MVC-site, but when access /elmah, my site gets stuck in a redirect loop /elmah?culture=en - which I reckon is because of my one route config entry:

    public class  RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",
                "{culture}/{controller}/{action}/{id}",
                new { culture = CultureHelper.GetDefaultCulture(), controller = "Home", action = "SetCulture", id = UrlParameter.Optional }
            );
        }
    }

How should I modify RouteConfig to make /elmah display correctly? Or am I looking at the wrong place?

Thanks :-)


Solution

  • It was caused by a class called CultureAwareControllerActivator that implements IControllerActivator

    My knowledge is limited, but it seems that this class (which I added myself) connects to the request when the controller is activated and decides whether or not to modify and redirect.

    public class CultureAwareControllerActivator : IControllerActivator
    {
        public IController Create(RequestContext requestContext, Type controllerType)
        {
            string cultureName = requestContext.RouteData.Values["culture"] as string;
    
            // Attempt to read the culture cookie from Request
            if (cultureName == null)
                cultureName = requestContext.HttpContext.Request.UserLanguages != null && requestContext.HttpContext.Request.UserLanguages.Length > 0
                    ? requestContext.HttpContext.Request.UserLanguages[0]
                    : null; // obtain it from HTTP header AcceptLanguages
    
            // Validate culture name
            cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
    
    
            if (requestContext.RouteData.Values["culture"] as string != cultureName && (string) requestContext.RouteData.Values["controller"] != "Elmah")
            {
    
                // Force a valid culture in the URL
                requestContext.RouteData.Values["culture"] = cultureName.ToLowerInvariant(); // lower case too
    
                // Redirect user
                requestContext.HttpContext.Response.RedirectToRoute(requestContext.RouteData.Values);
            }
    
    
            // Modify current thread's cultures            
            Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    
            return DependencyResolver.Current.GetService(controllerType) as IController;
        }
    }