GithubHelp home page GithubHelp logo

boudinov / mvc-5-routing-localization Goto Github PK

View Code? Open in Web Editor NEW
10.0 2.0 2.0 399 KB

Simple localization and translation for both conventional and attribute static routing

C# 55.12% CSS 1.46% ASP 0.30% JavaScript 29.45% HTML 13.67%
mvc5 asp-net-mvc asp-net routing localization

mvc-5-routing-localization's Introduction

mvc-5-routing-localization

Simple localization and translation for both conventional and attribute static routing.

Features

Normal Route("~/invest") automatically(can opt out) gets a language prefix, such as /invest for default language, and e.g. /de/invest for german language. You can achieve the same for conventional routing.

For more control and/or url translation use LocalizeRoute("..."), so you can get /de/investieren, or disable route localization(opt out).

The effect is that you get Thread.CurrentThread.CurrentCulture and CurrentUICulture set appropriately during controller initialization.

Setup

Let's say we have a couple of languages we want to support, stored in application config, accessible like his:
ConfigurationManager.AppSettings["SupportedCultures"] -> "en,de"

We have a default culture like so:
ConfigurationManager.AppSettings["DefaultCulture"] -> "en"'

Have a resource files for these languages containing url path segments translated, e.g. for key 'invest' have it with default value 'invest', and in german resource file as 'investieren'

Add global filter:

filters.Add(new CultureFilter(ConfigurationManager.AppSettings["DefaultCulture"]);

Conventional routing

routes.MapRoute(
  name: "DefaultWithCulture",
  url: "{culture}/{controller}/{action}/{id}",
  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
  constraints: new { culture = new CultureConstraint(defaultCulture: ConfigurationManager.AppSettings["DefaultCulture"]) }
  );

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

Do this in same order in areas route registration too.

Attribute routing

In order for conventional and attribute routing to work together, initialize them in this order in global.asax.cs :

RouteTable.Routes.MapLocalizedMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);

By default, all normal routes are localized by adding a culture prefix e.g. for

[Route("~/invest")]

you have 2 routes generated:
~/{culture}/invest
~/invest (this one has a default route value of {culture} -> 'en')

Default culture urls by default have no language prefix - you can change this by setting PrefixDefaultCulture in web.config to true, so you will have /en/invest.

To have more control, use LocalizedRoute, usually for 2 scenarios:

1. Translate url path

[LocalizedRoute("~/invest")]
ActionResult Index() { ... }

generates these routes:
~/de/investieren
~/invest

2. Have a route that does not get prefix-localized, e.g. to permanent-redirect an old url to new one for SEO reasons.

For example if you need to redirect /investing to /invest. You can still opt out of url translation.

[LocalizeRoute("~/investing", explicitCulture: "en", translateUrl: false)
ActionResult Index_Old_en()
{
	return RedirectToActionPermanent("Index");
}

Ideas from post https://stackoverflow.com/questions/32764989/asp-net-mvc-5-culture-in-route-and-url

mvc-5-routing-localization's People

Contributors

boudinov avatar burakt91 avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

eugenemm burakt91

mvc-5-routing-localization's Issues

How to use it for dynamic translated routes

I'm using your project on one of my projects. It works great but I'm having problems integrating it on some of my dynamic routes. I have dynamic translated routes stored on a database table where there are also saved controller and the action names to use for every path.

Example for detail product page (default italian language):
https://www.mydomain.com/prodotti/nome-prodotto

English url:
https://www.mydomain.com/en/products/product-name

The path "product-name" is dynamic. It can also be "product-name-one", "bla-bla-bla" and so on. Product Id is not present in the route.
Question: If I am on the page https://mydomain.com/prodotti/nome-prodotto how do I point the language switch link to https://mydomain.com/en/products/product-name?

Thanks a lot

Default language to show in URL?

Is it possible to have a configuration switch or something that would force the generated URLs to include the default language? The example works fine with both "de" and "en" (default) but it would be great if "en" could always be written in rendered links.

Custom route prefix not working

This is a great routing example but I'm having problems getting this to work when I have specified a custom route prefix at the controller level.

When I have deep folder levels I can use route prefix such as /admin/dashboard/home. This works:

[RoutePrefix("admin/dashboard")]
    public class HomeController : Controller
    {
        [Route("home")]
        public ActionResult Index()
        {
            return View();
        }
    }

When I try and change to use a localized route, I receive 404s:

[LocalizedRoute("home")]
        public ActionResult Index()
        {
            return View();
        }
    }

I've tried different combinations of the URL being passed to LocalizedRoute but I think the RoutePrefix at the controller level is affecting the routing.

Just wondering if your library supports instances where you may have deep folders (more than the standard 2 levels deep) but still wish to localize the route?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.