简体   繁体   中英

How to localize the route action/controller in .NET Core

Searched but can't find any question specifically about localizing controller/actions rather than just adding the culture itself to URL.

I have a localized .NET Core website, by inserting /es/ into the URL (before controller/action is the way its set up ie www.bla.com/es/account/profile).

This uses culture settings and saves the culture in a cookie, and the site uses IStringLocalizer and it all works well.

My problem is, I now need to translate the route itself.

www.bla.com/account/profile

OR

www.bla.com/es/cuenta/perfil

(google translate just for example)

I don't think I am worried about translating any query strings or variable names at the moment, just the action and controller names themselves.

To add a middleware to rewrite the url, add this into your Startup.Configure method before UseRouting , UseRoute , or UseMvc depending on what is currently used:

//This definition should be moved as a field or property.
//And the value should be loaded dynamically.
var urlMappings = new Dictionary<string, string>
{
    { "/es/cuenta/perfil", "/account/profile" },
    // others
};

//Rewriting the matched urls.
app.Use(next => http =>
{
    if (urlMappings.TryGetValue(http.Request.Path.Value, out var result))
    {
        http.Request.Path = new PathString(result);
    }
    return next(http);
});

This is just an example on how to implement it, though url mapping rule should be managed within services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM