Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

IStringLocalizer returns key instead of value in Blazor Web Server app and is unable to find resource files

$
0
0

I have an IStringLocalizer in my app, injected through dependency injection in my TodoList page, that's supposed to provide localization for Italian and English.I'm having trouble getting it to work because for some reason, no matter what I rename the resource files to, it's unable to find them.

Here's my TodoList page's code, the only page where I use Localization:

@using BlazorPractice.Data@using BlazorPractice.Services@using Microsoft.Extensions.Localization@inject TodoService TodoService@inject IStringLocalizer<SharedResources> Localizer@page "/todolist"<h1>@Localizer["Title"]</h1><h3>@(string.Join(" ", Localizer.GetAllStrings().Select(v => v.ToString())))</h3><ul class="my-2" id="notes-list">    @foreach (var todoItem in _todoNotes)    {<TodoListItem TodoItem="@todoItem" OnDeleteNote="() => FetchNotesAsync()" OnToggleState="() => FetchNotesAsync()"></TodoListItem>    }</ul><EditForm class="my-2" Model="@_newNote" OnSubmit="@AddTodoItem"><div class="mb-3"><p class="form-label">@Localizer["Title"]</p><InputText @bind-Value="_newNote.Title"></InputText></div><div class="mb-3"><p class="form-label">@Localizer["Description"]</p><InputTextArea @bind-Value="_newNote.Description"></InputTextArea></div><div class="mb-3 form-label"><InputCheckbox class="d-inline-block" @bind-Value="_newNote.IsCompleted"></InputCheckbox><p class="form-label d-inline-block">@Localizer["IsCompleted"]</p></div><button class="btn btn-primary" type="submit">@Localizer["CreateNewNote"]</button><div class="text-danger my-2">@ErrorMessage</div></EditForm>@code {    TodoNote[] _todoNotes = { };    TodoNote _newNote = new();    private string ErrorMessage { get; set; } = string.Empty;    protected override async void OnInitialized()    {        _todoNotes = await TodoService.GetTodoNotesAsync();    }    async Task AddTodoItem()    {        if (!IsValidInput(_newNote.Title, Localizer["TitleRequired"]))            return;        if (!IsValidInput(_newNote.Description, Localizer["DescriptionRequired"]))            return;        await TodoService.AddTodoNoteAsync(_newNote);        _todoNotes = await TodoService.GetTodoNotesAsync();        _newNote = new TodoNote();        StateHasChanged();    }    private async void FetchNotesAsync()    {        _todoNotes = await TodoService.GetTodoNotesAsync();        StateHasChanged();    }    private bool IsValidInput(string input, string errorMessage)    {        if (!string.IsNullOrWhiteSpace(input)) return true;        ShowErrorMessage(errorMessage);        return false;    }    private async void ShowErrorMessage(string message)    {        ErrorMessage = message;        StateHasChanged();        await Task.Delay(2000);        ErrorMessage = string.Empty;    }}

And my Program.cs:

using Microsoft.AspNetCore.Components.Authorization;using Microsoft.AspNetCore.Identity;using Microsoft.EntityFrameworkCore;using BlazorPractice.Areas.Identity;using BlazorPractice.Data;using BlazorPractice.Services;using Microsoft.AspNetCore.Localization;var builder = WebApplication.CreateBuilder(args);// Add services to the container.var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");builder.Services.AddDbContext<ApplicationDbContext>(options =>    options.UseSqlite(connectionString));builder.Services.AddDatabaseDeveloperPageExceptionFilter();builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)    .AddEntityFrameworkStores<ApplicationDbContext>();builder.Services.AddHsts(options =>{    options.Preload = true;    options.IncludeSubDomains = true;    options.MaxAge = TimeSpan.FromDays(1);});builder.Services.AddRazorPages();builder.Services.AddServerSideBlazor();builder.Services    .AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();builder.Services.AddSingleton<WeatherForecastService>();builder.Services.AddScoped<TodoService>();builder.Services.AddLocalization(options =>{    options.ResourcesPath = "Resources";});var supportedCultures = new[] { "en", "it" };var localizationOptions = new RequestLocalizationOptions()    .SetDefaultCulture(supportedCultures[0])    .AddSupportedCultures(supportedCultures)    .AddSupportedUICultures(supportedCultures);builder.Services.Configure<RequestLocalizationOptions>(options =>{    options.DefaultRequestCulture = new RequestCulture(supportedCultures[0]);    options.SupportedCultures = localizationOptions.SupportedCultures;    options.SupportedUICultures = localizationOptions.SupportedUICultures;});var app = builder.Build();app.UseRequestLocalization(localizationOptions);// Configure the HTTP request pipeline.if (app.Environment.IsDevelopment()){    app.UseMigrationsEndPoint();}else{    app.UseExceptionHandler("/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.UseAuthentication();app.UseAuthorization();app.MapControllers();app.MapBlazorHub();app.MapFallbackToPage("/_Host");app.Run();

I tried renaming the files to BlazorPractice.Resources.Data.SharedAssets.en.resx and .it respectively, but this didn't work. I also tried to see if the GetAllStrings method of the Localizer would work to debug the issue, but I get an error saying "No manifests exist for the current culture."


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>