简体   繁体   English

使用Core 2.2本地化的Razor Page无法正常工作

[英]Razor Page using Core 2.2 Localization not working

I have a .NET Core 2.2 project 我有一个.NET Core 2.2项目

I have the following code in my startup 我的启动中有以下代码

ConfigurationServices method ConfigurationServices方法

services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();

Configuration method 配置方式

       app.UseStaticFiles();
        app.UseCookiePolicy();
        var supportedCultures = new[]
        {
            new CultureInfo("en-US"),
            new CultureInfo("es-ES"),
        };
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture("en-US"),
            // Formatting numbers, dates, etc.
            SupportedCultures = supportedCultures,
            // UI strings that we have localized.
            SupportedUICultures = supportedCultures
        });
        app.UseStaticFiles();
        app.UseStaticFiles();
        app.UseMvc();

I have in my Index Page.csHtml 我在索引Page.csHtml中

 @page
 @using Microsoft.AspNetCore.Mvc.Localization
 @model IndexModel
 @inject IViewLocalizer Localizer
 @{
     ViewData["Title"] = "Error";
 }
 <h3>Welcome to ASP.NET Localization</h3>
 <p>This is Localization</p>
 <h2>@Localizer["Overview"]</h2>

I am using the following methods in my Index.cshtml.cs 我在Index.cshtml.cs中使用以下方法

    private readonly IStringLocalizer<IndexModel> Localizer;
    public IndexModel(IStringLocalizer<IndexModel> localizer)
    {
        Localizer = localizer;
    }

I have created a Resource File 我已经创建了一个资源文件

\\Resources\\Index.es.resx \\资源\\ Index.es.resx

This currently has a key for Overview. 当前,这有一个概述键。

I load the app and try to change the culture as 我加载了该应用,并尝试更改文化

 https://localhost:44345/?culture=es-ES

But the string does not change as I would expect ! 但是字符串并没有像我期望的那样改变!

I'm using dotnet core2.1, the steps should be the same. 我使用的是dotnet core2.1,步骤应该相同。

  • create route culture provider: 创建路线文化提供商:
public class RouteValueRequestCultureProvider : IRequestCultureProvider
    {
        private readonly CultureInfo[] _cultures;

        public RouteValueRequestCultureProvider(CultureInfo[] cultures)
        {
            _cultures = cultures;
        }

        /// <summary>
        /// get {culture} route value from path string, 
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns>ProviderCultureResult depends on path {culture} route parameter, or default culture</returns>
        public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
        {
            var defaultCulture = "en";

            var path = httpContext.Request.Path;

            if (string.IsNullOrWhiteSpace(path))
            {
                return Task.FromResult(new ProviderCultureResult(defaultCulture));
            }

            var routeValues = httpContext.Request.Path.Value.Split('/');
            if (routeValues.Count() <= 1)
            {
                return Task.FromResult(new ProviderCultureResult(defaultCulture));
            }

            if (!_cultures.Any(x => x.Name.ToLower() == routeValues[1].ToLower()))
            {
                return Task.FromResult(new ProviderCultureResult(defaultCulture));
            }

            return Task.FromResult(new ProviderCultureResult(routeValues[1]));
        }
    }

  • Add RouteValueRequestCultureProvider to the top of cultures providers list: RouteValueRequestCultureProvider添加到区域性提供程序列表的顶部:
services.Configure<RequestLocalizationOptions>(ops =>
            {
                ops.DefaultRequestCulture = new RequestCulture("en");
                ops.SupportedCultures = cultures.OrderBy(x=>x.EnglishName).ToList();
                ops.SupportedUICultures = cultures.OrderBy(x => x.EnglishName).ToList();

                // add RouteValueRequestCultureProvider to the beginning of the providers list. 
                ops.RequestCultureProviders.Insert(0, 
                    new RouteValueRequestCultureProvider(cultures));
            });

public class CultureTemplateRouteModelConvention : IPageRouteModelConvention
    {
        public void Apply(PageRouteModel model)
        {
            var selectorCount = model.Selectors.Count;
            for (var i = 0; i < selectorCount; i++)
            {
                var selector = model.Selectors[i];
                model.Selectors.Add(new SelectorModel
                {
                    AttributeRouteModel = new AttributeRouteModel
                    {
                        Order = -1,
                        Template = AttributeRouteModel.CombineTemplates(
                      "{culture?}",
                      selector.AttributeRouteModel.Template),
                    }
                });
            }
        }
    }

  • configure services to use the culture route template: 配置服务以使用区域性路由模板:
services.AddMvc()
        .AddRazorPagesOptions(o => {
            o.Conventions.Add(new CultureTemplateRouteModelConvention());
        });

see full tutorial here . 在这里看到完整的教程。

  • for creating the language drop down, you can either create it manually as described here or you may use this nugget package to create it automatically with less code :) 要创建语言下拉列表,您可以按照此处所述手动创建,也可以使用此块软件包以更少的代码自动创建它:)

Localizations for razor pages should be located in Pages folder. 剃须刀页面的本地化应该位于Pages文件夹中。 So localizations for Index razor page should be located at 因此,“ Index剃刀页面的本地化应该位于

\Resources\Pages\Index.es.resx

通过链接的教程,您正在使用共享资源,因此您不应在用于页面等的资源中创建子文件夹,而仅将每个resx文件命名为ViewResource.xx.resx。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 本地化文件无法在MVC ASP.NET Core 2.2中呈现Razor页面 - Localization file not effective rendering a Razor page in MVC ASP.NET Core 2.2 本地化ASP.NET Core 2.2不适用于视图模型和视图 - Localization ASP.NET Core 2.2 not working for viewmodels and views Razor 对 asp.net 核心 2.2 中的 Controller 的页面表单操作 - Razor Page form action to Controller in asp.net core 2.2 .Net Core 2.2。 调用Identity Razor页面Ajax方法 - .Net Core 2.2. Calling Identity Razor page ajax methods Asp .Net Core 2.2 Razor页面Ajax呼叫发布不起作用 - Asp .Net Core 2.2 Razor Pages Ajax Call Post not working 使用 Razor Pages 在 Asp.NET Core 2.2 中找不到 ViewComponent - ViewComponent not found in Asp.NET Core 2.2 using Razor Pages Razor Pages 中的 Asp.net 核心本地化 - Asp.net core Localization in Razor Pages .NET Core 2.2 Razor 后面的页面代码创建文本文件,但无法将简单的行写入文件 - .NET Core 2.2 Razor Page Code Behind Creates Text File, But Fails to Write Simple Line To File CS1525 剃刀视图页面 ASP.NET-core 2.2 中的表达式术语“&gt;”无效 - CS1525 Invalid expression term '>' in razor view page ASP.NET-core 2.2 当特定的数据库字段更改时,重新加载ASP.NET Core Razor 2.2网页的最佳方法 - Best way to reload ASP.NET Core Razor 2.2 web page when specific database field changes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM