Use LazZiya.ExpressLocalization developing multilingual ASP.NET Core 2.x project

table of Contents

Introduction

background

Create a project

Installation LazZiya.ExpressLocalization

Create a localized resource

Using the code

Add language navigation

Localization view

Localization URL

Localization identification (the Identity) View

Notes localized data

Client Authentication

The sample project


Introduction

The development of multi-language SP.NET Core 2.x Web application requires a lot of infrastructure set up, and it takes time and effort. In this article, we will use LazZiya.ExpressLocalization NuGet package further localize our Web application.

background

Most Web applications use based URL localized, so we can URL to view the selected cultures, such as http://www.example.com/en/Contact . Unfortunately, ASP.NET Core only requested to provide the following cultural Provider:

  • QueryStringRequestCultureProvider
  • CookieRequestCultureProvider
  • AcceptLanguageHeaderRequestCultureProvider

In order to achieve localization routing, we need to build a custom localization provider and define the global routing template, so basically, we need to complete the following steps in order to have a fully localized localization of Web applications:

  • Builders routing requests culture provides value
  • For the culture to define the global routing template parameters
  • Set DataAnnotations Localization
  • Set ModelBinding localized error messages
  • Setting an error message describing identity
  • Set View localization
  • Setting up the client-side validation script to verify the localization of numbers, dates, and so on.
  • Provide localized resources for each section

All of these steps require a lot of work and takes too much time. Therefore, LazZiya.ExpressLocalization NuGet benefits package is that it eliminates the time and effort locale by a simple line of code.

Create a project

Let's start by creating a basic ASP.NET Core 2.2 Web applications (I'm using VS2019 ):

1, by selecting the ASP.NET Core Web Application Create a new project:

2, click on the Next , specify a friendly name for the project, and then click the Create :

3, select the Web application and ensure that the authentication changes to individual user accounts.

4、单击Create并等待解决方案创建基本模板,完成后,您可以通过在解决方案资源管理器中选择项目名称来执行测试运行,然后按(Ctrl + B)构建项目,然后(Ctrl + W)在浏览器中无需调试即可运行。

安装LazZiya.ExpressLocalization

1、在项目名称下的解决方案资源管理器中,右键单击Dependencies并选择Manage Nuget Packages ”

2、转到浏览选项卡并搜索LazZiya,选择LazZiya.ExpressLocalization并单击安装,选择最新版本(撰写本文时的v1.1.1):

3、它将要求安装两个软件包,单击确定和等待安装完成:

  1. LazZiya.ExpressLocalization (所有本地化设置都需要)
  2. LazZiya.TagHelpers (客户端本地化验证和语言下拉列表所需)

创建本地化资源

我已经为项目准备了本地化资源,因此您不必浪费时间来创建本地化资源。

在项目根目录下,创建一个新文件夹并将其命名为LocalizationResources

LocalizationResources文件夹下,创建新public类并将其命名为ViewLocalizationResource,此类将用于对资源文件进行分组以进行视图本地化:

namespace ExpressLocalizationSample.LocalizationResources
{
    public class ViewLocalizationResource
    {
    }
}

LocalizationResources文件夹下,创建新public类并将其命名为ExpressLocalizationResource,此类将用于将资源文件分组以进行标识、模型绑定和数据注释。

namespace ExpressLocalizationSample.LocalizationResources
{
    public class ExpressLocalizationResource
    {
    }
}

我们将使用这两个类将资源类型传递给快速定位方法。

最后,从此存储库文件夹下载相关的文化资源。请注意,您需要为每种文化下载两个文件,例如(ExpressLocalizationResource.tr.resxViewLocalizationResource.tr.resx)。将下载的文件复制到LocalizationResources ”文件夹。

使用代码

最后,我们已准备好进行本地化设置。:)

打开startup.cs文件并添加所需的文化列表,然后添加一步本地化设置,如下所示:

var cultures = new[]
{
    new CultureInfo("tr"),
    new CultureInfo("ar"),
    new CultureInfo("hi"),
    new CultureInfo("en"),
};

services.AddMvc()
    .AddExpressLocalization<ExpressLocalizationResource, ViewLocalizationResource>(
    ops =>
    {
        ops.ResourcesPath = "LocalizationResources";
        ops.RequestLocalizationOptions = o =>
        {
            o.SupportedCultures = cultures;
            o.SupportedUICultures = cultures;
            o.DefaultRequestCulture = new RequestCulture("en");
        };
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

然后在Configure方法下,配置应用程序以使用请求本地化:

app.UseRequestLocalization();

添加语言导航

Pages文件夹下,打开_ViewImports.cshtml文件并添加LazZiya.TagHelpers它将有助于创建语言导航:

@using LazZiya.TagHelpers
@addTagHelper *, LazZiya.TagHelpers

然后打开Pages / Shared / _Layout.cshtml文件,并在标签下添加语言导航标签助手_LoginPartial,如下所示:

<partial name="_LoginPartial" />
<language-nav view-context="ViewContext"></language-nav>

LanguageNav有一个必需参数view-context,阅读有关LanguageNav标记助手的更多信息。

我们准备第一次运行:

这么好,到目前为止我们的导航支持文化,但我们仍然需要本地化视图文本以查看本地化版本。

本地化视图

已下载文件的ViewLocalizationResource.xx.resx ”中已提供默认项目的本地化文本。如果需要为视图添加更多自定义文本,请将它们添加到ViewLocalizationResource.xx.resx ”文件中。

打开Pages / _ViewImports.cshtml文件并注入ExpressLocalization已经附带的SharedCultureLocalizer

@using LazZiya.ExpressLocalization

@inject SharedCultureLocalizer _loc

然后打开Pages / Index.cshtml并使用文本的localizer函数:

@page
@model IndexModel
@{
    ViewData["Title"] = _loc.Text("Home page");
}

<div class="text-center">
    <h1 class="display-4">@_loc.Text("Welcome")</h1>
    <p>@_loc.Text("Learn about 
    <a href='https://docs.microsoft.com/aspnet/core'>
     building Web apps with ASP.NET Core</a>").</p>
</div>

使用相同的过程来本地化其他视图中的所有文本。

本地化URL

当页面处于默认设置以外的任何区域性时,如果单击隐私登录注册链接,您将注意到我们正在丢失所选文化,这是因为我们未将文化路由值添加到链接。

打开Pages / _ViewImports.cshtml并添加引用System.Globalization

@using System.Globalization

然后打开Pages / _LoginPartial.cshtml并在页面顶部添加一个culture参数,如下所示:

@{
    var culture = CultureInfo.CurrentCulture.Name;
}

使用此参数为culture所有链接提供路由值,如下所示:

<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register"
    asp-route-culture="@culture">@_loc.Text("Register")</a>

对项目中的所有视图执行此操作。

本地化标识(Identity)视图

需要对登录,注册和配置文件等相关标识进行搭建才能进行修改。

右键单击项目名称,选择Add - > New Scaffolded Item ...

选择Identity并单击Add

选择覆盖所有文件 ”并选择ApplicationDbContext

单击添加,将创建一个新的Areas文件夹,包括所有与标识相关的视图:

标识区域有三个_ViewImports文件夹:

  • Areas/Identity/Pages/_ViewImports.cshtml
  • Areas/Identity/Pages/Account/_ViewImports.cshtml
  • Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml

像以前对Pages / _ViewImports.cshtml所做的那样,将以下代码添加到所有代码中:

@using System.Globalization

@using LazZiya.TagHelpers
@addTagHelper *, LazZiya.TagHelpers

@using LazZiya.ExpressLocalization
@inject SharedCultureLocalizer _loc

像以前一样浏览视图并使用本地化步骤来本地化视图并添加culture路由参数。以下是Register.cshtml页面:

@page
@model RegisterModel
@{
    ViewData["Title"] = _loc.Text("Register");
    var culture = CultureInfo.CurrentCulture.Name;
}

<h1>@ViewData["Title"]</h1>

<div class="row">
    <div class="col-md-4">
        <form asp-route-returnUrl="@Model.ReturnUrl" 

        method="post" asp-route-culture="@culture">
            <h4>@_loc.Text("Create a new account").</h4>
            <hr />
            <div asp-validation-summary="All" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Input.Email"></label>
                <input asp-for="Input.Email" class="form-control" />
                <span asp-validation-for="Input.Email" 

                class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.Password"></label>
                <input asp-for="Input.Password" class="form-control" />
                <span asp-validation-for="Input.Password" 

                class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Input.ConfirmPassword"></label>
                <input asp-for="Input.ConfirmPassword" class="form-control" />
                <span asp-validation-for="Input.ConfirmPassword" 

                class="text-danger"></span>
            </div>
            <button type="submit" 

            class="btn btn-primary">@_loc.Text("Register")</button>
        </form>
    </div>
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

本地化数据注释

如果你运行页面,并做一些无效的输入,你会发现,验证消息都是英文的,所以我们需要本地化的数据注解的消息,如RequiredStringLength等。

打开Areas/Identity/Pages/Account/Register.cshtml.cs文件,并在页面顶部添加对LazZiya.ExpressLocalization.Messages的引用它包含一个以便于使用的所有DataAnnotations错误消息的预定义struct

@using LazZiya.ExpressLocalization.Messages;

然后修改输入模型,如下所示:

public class InputModel
{
    [Required(ErrorMessage = DataAnnotationsErrorMessages.RequiredAttribute_ValidationError)]
    [EmailAddress(ErrorMessage = DataAnnotationsErrorMessages.EmailAddressAttribute_Invalid)]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required(ErrorMessage = DataAnnotationsErrorMessages.RequiredAttribute_ValidationError)]
    [StringLength(100, ErrorMessage = 
           DataAnnotationsErrorMessages.StringLengthAttribute_ValidationErrorIncludingMinimum,
           MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", 
     ErrorMessage = DataAnnotationsErrorMessages.CompareAttribute_MustMatch)]
    public string ConfirmPassword { get; set; }
}

编译并运行项目,您将看到本地化数据注释错误消息:

客户端验证

服务器端验证工作正常,但我们仍然需要添加客户端验证,因此在提交表单之前,将在客户端验证输入字段。

客户端验证的一个主要问题是验证本地化输入,如数字、日期等。例如,如果您使用的是十进制输入,您将看到本地化数字(如1.3)的验证错误在英语区域中有效,但对于土耳其语无效,因为它应该是1,3(逗号而不是句点)。

在这里,我们将使用另一个有用的标签助手LazZiya.TagHelpers

打开Register.cshtml页面并在默认验证脚本partial下添加标签助手:

@section Scripts {

    <partial name="_ValidationScriptsPartial" />
    <localization-validation-scripts></localization-validation-scripts>
}

这就是全部,现在将在使用本地化验证消息提交表单之前验证字段:

示例项目

您可以从GitHub下载包含超过19种文化的示例项目:

 

原文地址:https://www.codeproject.com/Articles/5061604/Developing-Multicultural-ASP-NET-Core-2-x-Project

Guess you like

Origin blog.csdn.net/mzl87/article/details/90779671