【问题标题】:Mvc: Same ActionResult with different name depending urlMvc:相同的 ActionResult 具有不同的名称,具体取决于 url
【发布时间】:2013-05-10 13:33:38
【问题描述】:

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

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

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

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

www.something.com/co/es/noticias 西班牙语版

你知道接下来的国家。

我认为我不需要创建 x 方法 依赖于完全相同的 x url,但我不知道如何真正实现它有效的方法...谢谢

【问题讨论】:

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


    【解决方案1】:

    您的路由现在如何工作?如果您还没有使用它,也许像 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
        }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-19
        • 2017-05-27
        • 2019-09-03
        • 1970-01-01
        • 1970-01-01
        • 2011-11-20
        相关资源
        最近更新 更多