Location>code7788 >text

Abp source code analysis of Abp localization

Popularity:808 ℃/2024-11-12 10:00:08

aspnetcore mvc localization

New mvc project

modifications

using ;
using ;
using ;

var builder = (args);

var supportedCultures = new[]
{
    new CultureInfo("zh-CN"),
    new CultureInfo("en-US"),
};
<RequestLocalizationOptions>(options =>
{
     = new RequestCulture("zh-CN");
     = supportedCultures;
     = supportedCultures;
});

(options =>  = "Resources");

()
        .AddViewLocalization()
        .AddDataAnnotationsLocalization();

var app = ();

();

if (!())
{
    ("/Home/Error");
    ();
}

();
();

();

();

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


();

Localization-related code

var supportedCultures = new[]
{
    new CultureInfo("zh-CN"),
    new CultureInfo("en-US"),
};
<RequestLocalizationOptions>(options =>
{
     = new RequestCulture("zh-CN");
     = supportedCultures;
     = supportedCultures;
});

(options =>  = "Resources");

()
        .AddViewLocalization()
        .AddDataAnnotationsLocalization();
();

Create a new Resources directory with the following contents

modifications

@using 
@using 
@using 

@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>

Visit the home page

Using Json Resource Files

New mvc project

installer

I downloaded the source code for research convenience, so I referenced the source project, and all we need to do for official use is to install the nuget package

modifications

using ;
using ;
using ;
using ;


var builder = (args);

var services = ;

// Add services to the container.
();

var supportedCultures = new[]
{
    new CultureInfo("zh-CN"),
    new CultureInfo("en-US"),
};
<RequestLocalizationOptions>(options =>
{
     = new RequestCulture("zh-CN");
     = supportedCultures;
     = supportedCultures;
});
var resourcesPath = ("ResourcesPath") ?? "Resources";
(options =>
{
     = resourcesPath;
    //  = ;
     = ;
});

()
    .AddMvcLocalization(options =>
    {
         = resourcesPath;
    }, );

var app = ();

();



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

();
();

();

();

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

();

It differs from the original aspnetcore code in only a few ways

(options => = "Resources");
change into:
(options =>
{
     = resourcesPath;
    // = ;
     = ;
});

Resource Document File Directory

Content:

source code analysis

is to write a class JsonStringLocalizerFactory implements IStringLocalizerFactory

Wrote JsonStringLocalizer which implements IStringLocalizer.

Load the json file in GetResources of the JsonStringLocalizer class.


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

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

            if ((_searchedLocation))
            {
                try
                {
                    using var stream = (_searchedLocation);
                    value = <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;
        });
    }

ABP Localization

Create a new mvc project Import the following four packages

## New construction

using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

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

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

            ConfigureVirtualFileSystem(hostingEnvironment);

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

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

                 = typeof(BookStoreResource);
            });

            //()
            // .AddMvcLocalization(options =>
            // {
            // = "/Localization/BookStore";
            // }, );

            //Configure<AbpExceptionLocalizationOptions>(options =>
            //{
            // ("BookStore", typeof(BookStoreResource));
            //});
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = ();
            var env = ();

            ();

            if (())
            {
                ();
            }

            ();
            ();

            ();
        }

        private void ConfigureVirtualFileSystem(IWebHostEnvironment hostingEnvironment)
        {
            Configure<AbpVirtualFileSystemOptions>(options =>
            {
                <BookAppWebModule>();

                if (())
                {
                    <BookAppWebModule>();
                }
            });
        }
    }
}

modifications

using BookApp;
using ;

var builder = (args);


    .AddAppSettingsSecretsJson()
    .UseAutofac();

await <BookAppWebModule>();

var app = ();

await ();

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

await ();

New Resource Files and Catalogs

element

We only use AppName.

newly built

using ;

namespace ;

[LocalizationResourceName("BookStore")]
public class BookStoreResource
{

}

modifications

@using 
@using 
@using 
@using 

@inject IHtmlLocalizer<BookStoreResource> HtmlLocalizer
@inject IStringLocalizer<BookStoreResource> StringLocalizer
@inject IViewLocalizer ViewLocalizer
@{
    ViewData["Title"] = "Home Page";
}

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

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

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

display effect

source code analysis

center

using ;
using ;
using ;
using ;
using ;

namespace ;

[DependsOn(
    typeof(AbpVirtualFileSystemModule),
    typeof(AbpSettingsModule),
    typeof(AbpLocalizationAbstractionsModule),
    typeof(AbpThreadingModule)
    )]
public class AbpLocalizationModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        ();

        Configure<AbpVirtualFileSystemOptions>(options =>
        {
            <AbpLocalizationModule>("", "Volo/Abp");
        });

        Configure<AbpLocalizationOptions>(options =>
        {
            options
                .Resources
                .Add<DefaultResource>("en");

            options
                .Resources
                .Add<AbpLocalizationResource>("en")
                .AddVirtualJson("/Localization/Resources/AbpLocalization");
        });
    }
}

We look at the content of the ();;'s

    internal static void Replace(IServiceCollection services)
    {
        (<IStringLocalizerFactory, AbpStringLocalizerFactory>());
        <ResourceManagerStringLocalizerFactory>();
    }

We find that the custom AbpStringLocalizerFactory implements IStringLocalizerFactory

AbpDictionaryBasedStringLocalizerRealizedIStringLocalizer

Tracking GetLocalizedString()

Read the json file here

Related articles

[Understanding Core - Globalization and Localization] (Understanding Core - Globalization and Localization - xiaoxiaotank - Blogspot)

author

Wu Xiaoyang (cell phone: 13736969112 wechat the same number)