Search code examples
c#asp.net-mvcglobal-asaxrouteconfig

How to set default language in MVC RouteConfig?


I have a Language table on my database. There is one primary language. My software on layered architecture. Layers : Domain-Data(Repository)-Business-Presentation And I am using Ninject for DI.

So, I should get primary language while application start and set my url like : {language}/{controller}/{action}/{id}

How can I do this? Because I couldn't access to my business layer on RouteConfig.cs or Global.asax Is there a way to do this?

I want to do like this:

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

            routes.MapRoute(
                name: "Default",
                url: "{language}/{controller}/{action}/{id}",
                defaults: new { language = _languageBusiness.GetPrimaryLanguageCode(), controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

Solution

  • I solved the issue. RouteConfig file should be like that to get primary language.

    public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                var languageBusiness = DependencyResolver.Current.GetService<ILanguageBusiness>();
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    name: "Default",
                    url: "{language}/{controller}/{action}/{id}",
                    defaults: new { language = languageBusiness.GetPrimaryLanguage().Code, controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
            }
        }