如何在.net core中的Url中显示当前的文化?

时间:2019-05-16 06:01:21

标签: asp.net-core routing localization globalization

我正在尝试在.Netcore中实现本地化,但是我陷入一件事,即我将如何在Url中显示当前的文化。我已经检查并尝试了许多方法,但无法使其正常工作。我将展示我已实现的内容。

在我的启动ConfigureConfigs下:

services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();

services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[]
    {
        new CultureInfo("de"),
        new CultureInfo("en")
    };

    options.DefaultRequestCulture = new RequestCulture(culture: "de", uiCulture: "de");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
    options.RequestCultureProviders = new List<IRequestCultureProvider>
    {
        new QueryStringRequestCultureProvider(),
        new CookieRequestCultureProvider()
    };
});

启动配置:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
    app.UseRequestLocalization(locOptions.Value);
    var culture = locOptions.Value.DefaultRequestCulture.Culture;

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseStaticFiles();
    app.UseSession();

    //configuring mvc routes...
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "areaRoute",
            template: "{area:exists}/{controller}/{action}/{id?}",
            defaults: new { controller = "Home", action = "Index" });

        routes.MapRoute(
            name: "default",
            template: "{culture}/{controller}/{action}/{id?}",
            defaults: new { culture = culture, controller = "Home", action = "Index" });
    });
}

我已经创建了局部视图,并且正在像不断成功地改变这种文化那样改变文化:-

[HttpPost]
public IActionResult ChangeLanguage(string culture, string returnUrl)
{
    Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
    );

    return LocalRedirect(returnUrl);
}

现在,我想在网址中显示我当前的文化,例如www.test.com/en/home/view

我创建了一条路线并设置了区域性,但是即使我更改了区域性,它也仅采用默认区域性。

也请告诉我这是实现本地化的一种正确方法,因为我对此话题太困惑了。

编辑:-我只需要在更改应用程序的区域性时更改url中的区域性即可。

2 个答案:

答案 0 :(得分:0)

我认为您的配置应该喜欢

    CultureInfo[] supportedCultures = new[]
    {
        new CultureInfo("nl"),
        new CultureInfo("en")
    };

    services.Configure<RequestLocalizationOptions>(options =>
    {
        options.DefaultRequestCulture = new RequestCulture("nl"); // your language here
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
        options.RequestCultureProviders = new List<IRequestCultureProvider>
        {
            new QueryStringRequestCultureProvider(), // support query string to change language
            new CookieRequestCultureProvider()
        };
    });
  

QueryStringRequestCultureProvider

     

某些应用将使用查询字符串来   设置文化和用户界面文化。对于使用Cookie或   Accept-Language标头方法,向URL添加查询字符串是   对于调试和测试代码很有用。默认情况下,   QueryStringRequestCultureProvider注册为第一个   RequestCultureProvider列表中的本地化提供程序。你通过了   查询字符串参数文化和用户界面文化。下面的例子   将特定的文化(语言和地区)设置为西班牙语/墨西哥:

     

http://localhost:5000/?culture=es-MX&ui-culture=es-MX

     

如果您仅传入两者之一(区域性或ui-culture),则查询   字符串提供程序将使用您传入的值设置两个值。   例如,仅设置文化将设置文化和   UICulture:

     

http://localhost:5000/?culture=es-MX

答案 1 :(得分:0)

在配置中删除var culture = locOptions.Value.DefaultRequestCulture.Culture;,该设置始终将区域性设置为默认区域性。

下面的演示适用于使用twoLetterLanguageName。请参阅此tutorial

1。创建一个RouteDataRequestCultureProvider类:

public class RouteDataRequestCultureProvider : RequestCultureProvider
{
    public int IndexOfCulture;
    public int IndexofUICulture;

    public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException(nameof(httpContext));

        string culture = null;
        string uiCulture = null;

        var twoLetterCultureName = httpContext.Request.Path.Value.Split('/')[IndexOfCulture]?.ToString();
        var twoLetterUICultureName = httpContext.Request.Path.Value.Split('/')[IndexofUICulture]?.ToString();

        if (twoLetterCultureName == "de")
            culture = "de-DE";
        else if (twoLetterCultureName == "en")
            culture = uiCulture = "en-US";

        if (twoLetterUICultureName == "de")
            culture = "de-DE";
        else if (twoLetterUICultureName == "en")
            culture = uiCulture = "en-US";

        if (culture == null && uiCulture == null)
            return NullProviderCultureResult;

        if (culture != null && uiCulture == null)
            uiCulture = culture;

        if (culture == null && uiCulture != null)
            culture = uiCulture;

        var providerResultCulture = new ProviderCultureResult(culture, uiCulture);

        return Task.FromResult(providerResultCulture);
    }
}

2。还有一个LanguageRouteConstraint

public class LanguageRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
    {

        if (!values.ContainsKey("culture"))
            return false;

        var culture = values["culture"].ToString();
        return culture == "en" || culture == "de";
    }
}

3.startup.cs:

services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new List<CultureInfo>
    {
        new CultureInfo("en"),
        new CultureInfo("de"),
    };

    options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en-US");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;

    options.RequestCultureProviders = new[]{ new RouteDataRequestCultureProvider{
        IndexOfCulture=1,
        IndexofUICulture=1
    }};

});

services.Configure<RouteOptions>(options =>
{
    options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint));
});

services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
        options.Conventions.AddAreaFolderRouteModelConvention("Identity", "/Account/", model =>
        {
            foreach (var x in model.Selectors)
            {
                if (x.AttributeRouteModel.Template.StartsWith("Identity"))
                {
                    x.AttributeRouteModel = new AttributeRouteModel()
                    {
                        Order = -1,
                        Template = AttributeRouteModel.CombineTemplates(("{culture=en}"),
                            x.AttributeRouteModel.Template)
                    };
                }
            }
        });
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);  

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "MyArea",
        template: "{culture:culture}/{area:exists}/{controller=Home}/{action=Index}/{id?}");

    routes.MapRoute(
            name: "LocalizedDefault",
            template: "{culture:culture}/{controller}/{action}/{id?}");

    routes.MapRoute(
            name: "default",
            template: "{controller}/{action}/{id?}",
            defaults: new { controller = "Home", action = "Index" });
});

然后,您可以直接使用/en/Home/Privacy更改浏览器网址中的区域性。

4。要显示文化,请在ChangeLanguage操作中将重定向网址修改为包含文化:

[HttpPost]
    public IActionResult SetLanguage(string culture, string returnUrl)
    {

        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
        );
        var array = returnUrl.Split("/");
        if (array[1] == "en" || array[1] == "de")//returnUrl like ~/en/Home/privacy
        {
            array[1] = culture;
            return LocalRedirect(String.Join("/", array));
        }
        else// returnUrl like ~/Home/privacy
        {
            return LocalRedirect("/" + culture + returnUrl.Substring(1));
        }

    }

5.set asp-area用于_SelectLanguagePartial.cshtml中的操作,如果操作位于根区域,则使用asp-area=""

<form id="selectLanguage" asp-area="" asp-controller="Home" ...>...
</form>