[ASP.NET Core]實作基礎ASP.net Core 多國語系(1)

ASP.net  Core系列

先在Startu的ConfigureServices加入以下片段
 

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //加入區段
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddMvc()
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

            services.Configure<RequestLocalizationOptions>(
                opts =>
                {
                    var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en-US"),
                        new CultureInfo("zh-TW")
                    };
                    opts.SupportedCultures = supportedCultures;
                    opts.SupportedUICultures = supportedCultures;
                });
        }

AddLocalization:主要的多國語言服務,ResourcesPath 是指定資源檔的目錄位置

AddViewLocalization:要在View裡面使用多語系。

在Startup中加入Configure()

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                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();
            //加入此片段
            var requestLocalizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
            app.UseRequestLocalization(requestLocalizationOptions);
            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

ASP.NET Core Web 專案中建立 Resources 資料夾,加入Views.Shared._Layout.en-US.resx
和 Views.Shared._Layout.zh-TW.resx , Views.Shared._Layout.resx 文件,加入"SiteTitle" :



執行結果看看

元哥的筆記