Created
December 29, 2025 20:19
-
-
Save sunmeat/6893e4a1d714db35adba9c2c748d2a71 to your computer and use it in GitHub Desktop.
ASP.NET Core MVC + Localization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.AspNetCore.Localization; | |
| using Microsoft.EntityFrameworkCore; | |
| using mvc.Repository; | |
| using System.Globalization; | |
| // dotnet add package Microsoft.EntityFrameworkCore | |
| // dotnet add package Microsoft.EntityFrameworkCore.SqlServer | |
| // dotnet add package Microsoft.AspNetCore.Mvc.Localization | |
| // dotnet add package Microsoft.Extensions.Localization | |
| namespace mvc | |
| { | |
| public class Program | |
| { | |
| public static void Main(string[] args) | |
| { | |
| var builder = WebApplication.CreateBuilder(args); | |
| string? connection = builder.Configuration.GetConnectionString("DefaultConnection"); | |
| builder.Services.AddDbContext<StudentContext>(options => options.UseSqlServer(connection)); | |
| builder.Services.AddControllersWithViews(); | |
| builder.Services.AddScoped<IRepository, StudentRepository>(); | |
| // !!! | |
| builder.Services.AddLocalization(options => options.ResourcesPath = "Resources"); // !!! папка для .resx файлів | |
| // !!! | |
| builder.Services.AddMvc() | |
| .AddViewLocalization(LanguageViewLocationExpanderContext => { }) // для IViewLocalizer у views, щоб знаходив відповідні .resx файли | |
| .AddDataAnnotationsLocalization(); // для локалізації DisplayAttribute в моделях | |
| // !!! | |
| builder.Services.Configure<RequestLocalizationOptions>(options => | |
| { | |
| var supportedCultures = new[] | |
| { | |
| new CultureInfo("uk-UA"), | |
| new CultureInfo("en-US"), | |
| new CultureInfo("fr-FR") | |
| }; | |
| options.DefaultRequestCulture = new RequestCulture("uk-UA"); // українська за замовчуванням | |
| options.SupportedCultures = supportedCultures; | |
| options.SupportedUICultures = supportedCultures; | |
| // як визначається мова: query string (?culture=en-US), cookie, заголовок Accept-Language | |
| options.AddInitialRequestCultureProvider(new CustomRequestCultureProvider(async context => | |
| { | |
| return new ProviderCultureResult("uk-UA"); // fallback | |
| })); | |
| }); | |
| var app = builder.Build(); | |
| // !!! | |
| app.UseRequestLocalization(); // важливо: перед UseStaticFiles і MapControllerRoute! | |
| app.UseStaticFiles(); | |
| app.MapControllerRoute( | |
| name: "default", | |
| pattern: "{controller=Student}/{action=Index}/{id?}"); | |
| app.Run(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment