Blazor Server App中的全球化和本地化 [英] Globalization and Localization in Blazor Server App

查看:93
本文介绍了Blazor Server App中的全球化和本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Blazor Server App中进行全球化和本地化?

How to do globalization and localization in Blazor Server App ?

无法在Blazor Server App中找到全球化和本地化的有效示例,我创建了自己的一个.这是代码示例.复制并测试...

Not being able to find a working sample of globalization and localization in Blazor Server App, I've created one of my own. Here's the code sample. Copy and test...

推荐答案

  1. 创建一个文件夹并将其命名为Resources

  1. Create a folder and name it Resources

将以下资源文件( .resx )添加到文件夹 Pages.Index.resx :将字符串Greetings添加到Name列,然后问好!至值列

Add the following resource files (.resx) to the folder Pages.Index.resx: Add the string Greetings to the Name column and Hello! to the Value column

Pages.Index.fr.resx :将字符串Greetings添加到Name列和Bonjour!进入值"列

Pages.Index.fr.resx: Add the string Greetings to the Name column and Bonjour! to the Value column

Pages.Index.de.resx :将字符串Greetings添加到Name列和Hallo中进入值"列

Pages.Index.de.resx: Add the string Greetings to the Name column and Hallo to the Value column

将名为CultureSelector.razor的组件添加到共享"文件夹:

Add a component named CultureSelector.razor to the Shared folder:

CultureSelector.razor

@using  System.Globalization
@inject NavigationManager NavigationManager

@using System.Threading

<div>@SelectedCulture</div>

<select value="@SelectedCulture" @onchange="OnSelected">
    @foreach (var culture in Cultures)
    {
        <option value="@culture.Value">@culture.Caption</option>
    }
</select>


@code {

    private void OnSelected(ChangeEventArgs e)
    {
        var culture = (string)e.Value;
        var uri = new Uri(NavigationManager.Uri)
            .GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
        var query = $"?culture={Uri.EscapeDataString(culture)}&" +
            $"redirectUri={Uri.EscapeDataString(uri)}";

        NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);
    }

    public string SelectedCulture { get; set; } = Thread.CurrentThread.CurrentUICulture.Name;

    public class CultureData
    {
        public string Caption { get; set; }
        public string Value { get; set; }
    }

    public List<CultureData> Cultures { get; set; } = new List<CultureData>()
    {
        new  CultureData() { Caption = "English", Value = "en-US" },
        new  CultureData() { Caption = "French", Value = "fr-FR" },
        new  CultureData() { Caption = "German", Value = "de-DE" },
    };
}

像这样在MainLayout中实例化CultureSelector组件:

Instantiate the CultureSelector component in MainLayout like this:

@inherits LayoutComponentBase
@using System.Linq;
@using System.Reflection
@using Microsoft.AspNetCore.Components

<div class="sidebar">
    <NavMenu />
</div>

<div class="main">
    <div class="top-row px-4">
        <CultureSelector></CultureSelector>
        <a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
    </div>

    <div class="content px-4">
        @Body
    </div>
</div>

用法(Index.razor)

@page "/"
@using Microsoft.Extensions.Localization
@inject Microsoft.Extensions.Localization.IStringLocalizer<Index> localizer

<h1>@localizer["Greetings"].Value</h1>



@code{ }

Startrup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddLocalization(options => options.ResourcesPath = 
                                                      "Resources");
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddSingleton<WeatherForecastService>();
        services.AddControllers();
       
        services.Configure<RequestLocalizationOptions>(options =>
        {
            // define the list of cultures your app will support
            var supportedCultures = new List<CultureInfo>()
                                    {
                                         new CultureInfo("en-US"),
                                         new CultureInfo("fr-FR"),
                                         new CultureInfo("de-DE")
                                    };

            // set the default culture
            options.DefaultRequestCulture = new RequestCulture("en-US");

            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;
        });

    }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

      app.UseRequestLocalization(
     app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>> 
                                                                    ().Value);
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            // enable controllers for the culture controller
            endpoints.MapControllers();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }

将Controller类添加到Controllers文件夹(如果存在.如果不添加一个)将其命名为CultureController.cs

Add a Controller class to the Controllers folder (if exists. If not add one) Name it CultureController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace <Put here the namespace of your app>.Controllers
{
    [Route("[controller]/[action]")]
    public class CultureController : Controller
    {
        public IActionResult SetCulture(string culture, string redirectUri)
        {
            if (culture != null)
            {
                HttpContext.Response.Cookies.Append(
                    CookieRequestCultureProvider.DefaultCookieName,
                    CookieRequestCultureProvider.MakeCookieValue(
                        new RequestCulture(culture)));
            }

            return LocalRedirect(redirectUri);
        }
        public IActionResult ResetCulture(string redirectUri)
        {
            HttpContext.Response.Cookies.Delete(CookieRequestCultureProvider.DefaultCookieName);

            return LocalRedirect(redirectUri);
        }
    }
}

这篇关于Blazor Server App中的全球化和本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆