Mvc:具有不同名称的相同ActionResult,具体取决于url

时间:2013-05-15 20:17:25

标签: asp.net-mvc asp.net-mvc-4 url-rewriting routes url-routing

我想知道实现这一目标的最佳途径是什么。

我的控制器中有一个ActionResult,实际上它有news名称,现在我需要国际化我的网站,我不能拥有相同的news名称,它必须要根据所访问的国家/地区而变化。

例如,现在我需要类似的东西。

www.something.com/en/us/news英文版

西班牙语版本

www.something.com/co/es/noticias

你明确了下一个国家。

我认为我不需要根据 x urls 创建完全相同的 x方法,但我不知道如何真正实现它有效的方式...谢谢

2 个答案:

答案 0 :(得分:0)

您的路由现在如何运作?如果您还没有使用它,也许这样的answer会起作用。也许是这种变化的一部分,URL的各个部分以不同的顺序排列,以满足您的需求。例如,控制器不一定必须首先出现在路径中(或者根本不是,在这种情况下,总是使用相同的控制器名称)。使用语言代码作为关键,制作某种地图,以每种不同的语言为您提供“新闻”一词。

// populate this map somewhere - language code to word for "news" (and any other name of the controllers that you have)
var newsControllerMap = new Dictionary<string, string>();
newsControllerMap["en"] = "news"; // etc.

// ...

// inside of the RouteConfig class (MVC 4) or RegisterRoutes() method in Global.asax.cs (MVC 3)
// just making an assumption that whatever class/entity you use ("LanguageAndCountry" in this case) also has a country code to make this easier. Obviously this would be refactored to have better naming/functionality to make sense and meet your needs.
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    LanguageAndCountryRepository langRepo = new LanguageAndCountryRepository();
    var languagesandCountries = langRepo.GetAllLanguagesWithCountries();

    foreach (LanguageAndCountry langAndCountry in languagesandCountries)
    {
        routes.MapRoute(
        "LocalizationNews_" + langAndCountry.LanguageAbbreviation,
        langAndCountry.LanguageAbbreviation + "/" + langAndCountry.CountryCode + "/" + newsControllerMap[langAndCountry.LanguageAbbreviation],
        new { lang = language.LanguageAbbreviation, country = langAndCountry.CountryCode, controller = "News", action = "Index"});

        // map more routes to each controller you have, each controller having a corresponding map to the name of the controller in any given language
    }

答案 1 :(得分:0)

您可以创建一个新类TranslatedRoute和TranslationProvider,将不同的翻译映射到同一个动作。然后,您可以将它们插入路由系统并覆盖默认映射。

这是一篇很好的博客文章,描述了这个想法:http://blog.maartenballiauw.be/post/2010/01/26/Translating-routes-%28ASPNET-MVC-and-Webforms%29.aspx