【问题标题】:Netcore 2.2 Localized Routing - How to always redirect to default routeNet Core 2.2 本地化路由 - 如何始终重定向到默认路由
【发布时间】:2019-09-02 13:47:00
【问题描述】:

成功使用了Localized routing using ASP.NET Core MVC 2 上的项目,但是我想做一些修改,但我不清楚如何进行。

目前我的 start.cs 如下所示,这可以正常工作,但是它在默认文化英语中的作用是,我的路线是 www.site.com 而当我切换到任何其他文化时,我会得到 www.site.com /fr/accuel 或 www.site.com/es/casa...

如何让默认语言始终显示为 www.site.com/en/home

startup.cs

// Set up cultures
LocalizationRouteDataHandler.DefaultCulture = "en";
LocalizationRouteDataHandler.SupportedCultures = new Dictionary<string, string>()
{
    { "en", "English" },
    { "fr", "Français" },
    { "es", "Español" }
};

还有我的 HomeController

[AllowAnonymous]
[LocalizationRoute("en", "home")]
[LocalizationRoute("fr", "accueil")]
[LocalizationRoute("es", "casa")]
public class HomeController : LocalizationController
{
    [LocalizationRoute("en", "/home")]
    [LocalizationRoute("fr", "/accueil")]
    [LocalizationRoute("es", "/casa")]
    public IActionResult Index()
    {
        return View();
    }

【问题讨论】:

    标签: c# asp.net-core localization asp.net-core-localization


    【解决方案1】:

    对于LocalizationRoute,它定义了MVC的路由模板,用于将请求映射到动作。

    对于默认设计,请求/ 将被路由到具有英语文化的Home/Index。如果您更喜欢使用/en/home 显示网址,您需要通过以下代码重定向网址:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var options = new RewriteOptions()
        .AddRedirect(@"^$", $"{LocalizationRouteDataHandler.DefaultCulture}/{LocalizationRouteDataHandler.DefaultController}");           
    
        app.UseRewriter(options);
    
        var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(localizationOptions.Value);            
    
        //rest code
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}",
                defaults: new { culture = LocalizationRouteDataHandler.DefaultCulture }
            );
        });
    }
    

    注意以上方式,需要将[LocalizationRoute("en", "/home")]留给HomeController。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-11
      • 2015-01-31
      • 1970-01-01
      • 2018-02-14
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2021-02-22
      相关资源
      最近更新 更多