2016-05-12 6 views
1

У меня есть страница с несколькими языками, где я храню информацию о культуре в файле cookie. Но теперь я изменю его на локализацию URL. Веб-сайт должен выглядетьЛокализация URL в веб-проекте MVC

www.domain.com/en/home/index или www.domain.com/fr/home/index

я попробовал много решения, но ничего не получалось хорошо. Теперь у меня есть решение, но оно работает только в маршруте, но не с областями.

в Global.asax зарегистрировать маршруты, как

protected void Application_Start() 
    { 
    // ViewEngines.Engines.Clear(); 

     //LocalizedViewEngine: this is to support views also when named e.g. Index.de.cshtml 
     ViewEngines.Engines.Insert(0, new LocalizedViewEngine()); 

     AreaRegistration.RegisterAllAreas(); 

     RegisterGlobalFilters(GlobalFilters.Filters); 
     RegisterRoutes(RouteTable.Routes); 



     WebApiConfig.Register(GlobalConfiguration.Configuration); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     //standard mvc4 routing. see App_Start\RouteConfig.cs 
     //RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
     AuthConfig.RegisterAuth(); 
    } 



     public static void RegisterRoutes(RouteCollection routes) 
    { 
     const string defautlRouteUrl = "{controller}/{action}/{id}"; 

     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
     RouteValueDictionary defaultRouteValueDictionary = new RouteValueDictionary(new { controller = "Home", action = "Index", id = UrlParameter.Optional }); 
     routes.Add("DefaultGlobalised", new GlobalisedRoute(defautlRouteUrl, defaultRouteValueDictionary)); 
     routes.Add("Default", new Route(defautlRouteUrl, defaultRouteValueDictionary, new MvcRouteHandler())); 

     //LocalizedViewEngine: this is to support views also when named e.g. Index.de.cshtml 
     routes.MapRoute(
      "Default2", 
      "{culture}/{controller}/{action}/{id}", 
      new 
      { 
       culture = string.Empty, 
       controller = "Home",//ControllerName 
       action = "Index",//ActionName 
       id = UrlParameter.Optional 
      } 
     ).RouteHandler = new LocalizedMvcRouteHandler(); 
    } 

и в каждом AreaRegistration я это перезаписать

public override void RegisterArea(AreaRegistrationContext context) 
    { 
     context.MapRoute(
      "Doc_default", 
      "Doc/{controller}/{action}/{id}", 
      new { action = "Index", id = UrlParameter.Optional } 
     ); 

     //LocalizedViewEngine: this is to support views also when named e.g. Index.de.cshtml 
     context.MapRoute(
      "Doc_default2", 
      "{culture}/Doc/{controller}/{action}/{id}", 
      new 
      { 
       culture = string.Empty, 
       controller = "Doc", 
       action = "Index", 
       id = UrlParameter.Optional 
      } 
     ).RouteHandler = new LocalizedMvcRouteHandler(); 
    } 

Я проводил часы для этой проблемы, но я не понимаю! Есть ли хороший учебник для локализации URL MVC?

Спасибо за помощь!

+0

Вы можете использовать маршрутизацию атрибутов - [См. Статью здесь] (https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/) –

+0

Возможный дубликат [ASP.NET MVC 5 культура в маршруте и URL] (http://stackoverflow.com/questions/32764989/asp-net-mvc-5-culture-in-route-and-url) – NightOwl888

ответ

0

Итак, теперь у меня есть решение для меня. И это отлично работает.

меня сейчас в registerRroutes и RegisterArea

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

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

И тогда BaseController

protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state) 
    { 

     string cultureName; 
     if (RouteData.Values.ContainsKey("language") && !string.IsNullOrWhiteSpace(RouteData.Values["language"].ToString())) 
     { 
      cultureName = RouteData.Values["language"].ToString(); 
     } 
     else 
     { 
      cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ? CultureHelper.GetNeutralCulture(Request.UserLanguages[0]) : null; 
      cultureName = CultureHelper.GetImplementedCulture(cultureName); 
     } 

     Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName.ToLower()); 
     Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureName.ToLower()); 

     return base.BeginExecuteCore(callback, state); 
    } 

    protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     base.OnActionExecuting(filterContext); 

     var cultureName = CultureHelper.GetNeutralCulture(CultureHelper.GetCurrentCulture()); 
     cultureName = CultureHelper.GetImplementedCulture(cultureName); 
     filterContext.RouteData.Values["language"] = cultureName.ToUpper(); 
    } 

Вот это!

Смежные вопросы