.NET Core 本地化与类库

发布于 2025-01-16 16:34:59 字数 1096 浏览 2 评论 0原文

当资源文件夹位于 webUI 上时它工作正常。我如何将视图的资源文件存储在类库中。感谢您的帮助

[WebUI] [类库]

Program.cs

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

builder.Services.AddControllersWithViews()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, option =>
    {
        option.ResourcesPath = "Resources";
    })
    .AddDataAnnotationsLocalization()
     .AddRazorRuntimeCompilation();

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new(builder.Configuration["DefaultLanguage"]);

    CultureInfo[] cultures = new CultureInfo[]
    {
        new("en-US"),
        new("tr-TR"),
        new("fr-FR")
    };
        options.RequestCultureProviders = new List<IRequestCultureProvider>
        {
            new CookieRequestCultureProvider(),
        };
    options.SupportedCultures = cultures;
    options.SupportedUICultures = cultures;
});

It works fine when the resources folder is on the webUI.how do i store the resources file of my Views in class library . Thanks for help

[WebUI]
[Class Library]

Program.cs

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

builder.Services.AddControllersWithViews()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, option =>
    {
        option.ResourcesPath = "Resources";
    })
    .AddDataAnnotationsLocalization()
     .AddRazorRuntimeCompilation();

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new(builder.Configuration["DefaultLanguage"]);

    CultureInfo[] cultures = new CultureInfo[]
    {
        new("en-US"),
        new("tr-TR"),
        new("fr-FR")
    };
        options.RequestCultureProviders = new List<IRequestCultureProvider>
        {
            new CookieRequestCultureProvider(),
        };
    options.SupportedCultures = cultures;
    options.SupportedUICultures = cultures;
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空城仅有旧梦在 2025-01-23 16:34:59

这是我的工作演示,您可以参考:

ResourceLibrary:

在此处输入图像描述

SharedResource.cs ,将其放在项目的根文件夹中,不需要包含任何数据,只需包含类声明即可。

MVC项目,Program.cs

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

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization(); ;

var app = builder.Build();

// 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();
}
var supportedCultures = new[]
         {
                new CultureInfo("en-US"),
                new CultureInfo("de"),//you can add more language as you want...
            };

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("en-US"),
    // Formatting numbers, dates, etc.
    SupportedCultures = supportedCultures,
    // UI strings that we have localized.
    SupportedUICultures = supportedCultures
});
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

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

app.Run();

Controller本地化,首先添加对ResourceLibrary的引用。

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IStringLocalizer<SharedResource> _sharedLocalizer;
        public HomeController(ILogger<HomeController> logger, IStringLocalizer<SharedResource> sharedLocalizer)
        {
            _logger = logger;
            _sharedLocalizer = sharedLocalizer;
        }

        public IActionResult Index()
        {
            var value = _sharedLocalizer["Privacy"];
            return View();
        }
    }

索引本地化

@using Microsoft.Extensions.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using ResourceLibrary

@inject IStringLocalizer<SharedResource> Localizer
@inject IHtmlLocalizer<SharedResource> HtmlLocalizer

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

<div class="text-center">   
    <p>
        @HtmlLocalizer["Privacy Policy"]
    </p>
</div>

结果:

在此处输入图像描述

Here is my working demo , you could refer to :

ResourceLibrary:

enter image description here

SharedResource.cs , put it in the root folder of project and it does not need to contain any data, just the class declaration.

MVC project , Program.cs

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

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
                .AddDataAnnotationsLocalization(); ;

var app = builder.Build();

// 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();
}
var supportedCultures = new[]
         {
                new CultureInfo("en-US"),
                new CultureInfo("de"),//you can add more language as you want...
            };

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("en-US"),
    // Formatting numbers, dates, etc.
    SupportedCultures = supportedCultures,
    // UI strings that we have localized.
    SupportedUICultures = supportedCultures
});
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

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

app.Run();

Controller localization,first add reference to ResourceLibrary.

public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IStringLocalizer<SharedResource> _sharedLocalizer;
        public HomeController(ILogger<HomeController> logger, IStringLocalizer<SharedResource> sharedLocalizer)
        {
            _logger = logger;
            _sharedLocalizer = sharedLocalizer;
        }

        public IActionResult Index()
        {
            var value = _sharedLocalizer["Privacy"];
            return View();
        }
    }

Index localization

@using Microsoft.Extensions.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using ResourceLibrary

@inject IStringLocalizer<SharedResource> Localizer
@inject IHtmlLocalizer<SharedResource> HtmlLocalizer

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

<div class="text-center">   
    <p>
        @HtmlLocalizer["Privacy Policy"]
    </p>
</div>

result:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文