网站首页 全球最实用的IT互联网站!

人工智能P2P分享Wind搜索发布信息网站地图标签大全

当前位置:诺佳网 > 软件工程 > 后端开发 > .Net >

Abp源码分析之Abp本地化

时间:2024-11-12 09:29

人气:

作者:admin

标签:

导读:本文介绍了如何在 ASP.NET Core MVC 项目中实现本地化功能,包括使用资源文件和 JSON 文件两种方式。首先,通过修改 `Program.cs` 配置支持的多语言环境,并创建相应的资源文件目录。接着,...

新建mvc项目

修改Program.cs

using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
using System.Globalization;

var builder = WebApplication.CreateBuilder(args);

var supportedCultures = new[]
{
    new CultureInfo("zh-CN"),
    new CultureInfo("en-US"),
};
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new RequestCulture("zh-CN");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

builder.Services.AddControllersWithViews()
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization();

var app = builder.Build();

app.UseRequestLocalization();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");


app.Run();

跟本地化有关的代码

var supportedCultures = new[]
{
    new CultureInfo("zh-CN"),
    new CultureInfo("en-US"),
};
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new RequestCulture("zh-CN");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

builder.Services.AddControllersWithViews()
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization();
app.UseRequestLocalization();

新建Resources目录,内容如下

修改Index.cshtml

@using Microsoft.Extensions.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using WebApplication1.Controllers

@inject IHtmlLocalizer<HomeController> HtmlLocalizer
@inject IStringLocalizer<HomeController> StringLocalizer
@inject IViewLocalizer ViewLocalizer

@{
    ViewData["Title"] = "Home Page";
}

<div>string: @StringLocalizer["HelloWorld"]</div>

<div>html: @HtmlLocalizer["HelloWorld"]</div>

<div>view: @ViewLocalizer["HelloWorld"]</div>

访问首页

新建mvc项目

安装WeihanLi.Extensions.Localization.Json包

我为了研究方便,下载了源码,所以引用了源码项目,我们正式使用时只要安装nuget包就可以了

using System.Globalization;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
using WeihanLi.Extensions.Localization.Json;


var builder = WebApplication.CreateBuilder(args);

var services = builder.Services;

// Add services to the container.
builder.Services.AddControllersWithViews();

var supportedCultures = new[]
{
    new CultureInfo("zh-CN"),
    new CultureInfo("en-US"),
};
services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new RequestCulture("zh-CN");
    options.SupportedCultures = supportedCultures;
    options.SupportedUICultures = supportedCultures;
});
var resourcesPath = builder.Configuration.GetAppSetting("ResourcesPath") ?? "Resources";
services.AddJsonLocalization(options =>
{
    options.ResourcesPath = resourcesPath;
    // options.ResourcesPathType = ResourcesPathType.TypeBased;
    options.ResourcesPathType = ResourcesPathType.CultureBased;
});

services.AddControllersWithViews()
    .AddMvcLocalization(options =>
    {
        options.ResourcesPath = resourcesPath;
    }, LanguageViewLocationExpanderFormat.Suffix);

var app = builder.Build();

app.UseRequestLocalization();



// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

与aspnetcore原始的代码仅一下不同

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
改为:
services.AddJsonLocalization(options =>
{
    options.ResourcesPath = resourcesPath;
    // options.ResourcesPathType = ResourcesPathType.TypeBased;
    options.ResourcesPathType = ResourcesPathType.CultureBased;
});

资源文件文件目录

内容:

源码分析

就是写了一个类JsonStringLocalizerFactory实现了IStringLocalizerFactory

写了JsonStringLocalizer实现了IStringLocalizer

在JsonStringLocalizer类的GetResources中加载json文件


    private Dictionary<string, string> GetResources(string culture)
    {
        return _resourcesCache.GetOrAdd(culture, _ =>
        {
            var resourceFile = "json";
            if (_resourcesPathType == ResourcesPathType.TypeBased)
            {
                resourceFile = $"{culture}.json";
                if (_resourceName != null)
                {
                    resourceFile = string.Join(".", _resourceName.Replace('.', Path.DirectorySeparatorChar), resourceFile);
                }
            }
            else
            {
                resourceFile = string.Join(".",
                    Path.Combine(culture, _resourceName.Replace('.', Path.DirectorySeparatorChar)), resourceFile);
            }

            _searchedLocation = Path.Combine(_resourcesPath, resourceFile);
            Dictionary<string, string> value = null;

            if (File.Exists(_searchedLocation))
            {
                try
                {
                    using var stream = File.OpenRead(_searchedLocation);
                    value = JsonSerializer.Deserialize<Dictionary<string, string>>(stream);
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "Failed to get json content, path: {path}", _searchedLocation);
                }
            }
            else
            {
                _logger.LogWarning("Resource file {path} not exists", _searchedLocation);
            }

            return value;
        });
    }

新建mvc项目 导入下面四个包

## 新建BookAppWebModule.cs

using Volo.Abp.Localization.ExceptionHandling;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.VirtualFileSystem;
using Volo.Abp.Autofac;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Hosting.Internal;
using BookApp.Localization;

namespace BookApp
{
    [DependsOn(
        typeof(AbpAutofacModule),
        typeof(AbpLocalizationModule),
        typeof(AbpVirtualFileSystemModule),
        typeof(AbpAspNetCoreMvcModule)
    )]
    public class BookAppWebModule: AbpModule
    {
        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();
            var configuration = context.Services.GetConfiguration();

            context.Services.PreConfigure<AbpMvcDataAnnotationsLocalizationOptions>(options =>
            {
                options.AddAssemblyResource(
                    typeof(BookStoreResource)
                );
            });
        }
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var hostingEnvironment = context.Services.GetHostingEnvironment();

            ConfigureVirtualFileSystem(hostingEnvironment);

            Configure<AbpLocalizationOptions>(options =>
            {
                options.Languages.Add(new LanguageInfo("ar", "ar", "العربية"));
                options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština"));
                options.Languages.Add(new LanguageInfo("en", "en", "English"));
                options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)"));
                options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar"));
                options.Languages.Add(new LanguageInfo("fi", "fi", "Finnish"));
                options.Languages.Add(new LanguageInfo("fr", "fr", "Français"));
                options.Languages.Add(new LanguageInfo("hi", "hi", "Hindi"));
                options.Languages.Add(new LanguageInfo("it", "it", "Italiano"));
                options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português"));
                options.Languages.Add(new LanguageInfo("ru", "ru", "Русский"));
                options.Languages.Add(new LanguageInfo("sk", "sk", "Slovak"));
                options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe"));
                options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文"));
                options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文"));
                options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch"));
                options.Languages.Add(new LanguageInfo("es", "es", "Español"));

                options.Resources
                    .Add<BookStoreResource>("en")
                    .AddVirtualJson("/Localization/BookStore");

                options.DefaultResourceType = typeof(BookStoreResource);
            });

            //context.Services.AddControllersWithViews()
            //    .AddMvcLocalization(options =>
            //    {
            //        options.ResourcesPath = "/Localization/BookStore";
            //    }, LanguageViewLocationExpanderFormat.Suffix);

            //Configure<AbpExceptionLocalizationOptions>(options =>
            //{
            //    options.MapCodeNamespace("BookStore", typeof(BookStoreResource));
            / 
温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信