Skip to content

Instantly share code, notes, and snippets.

@LazZiya
Last active November 13, 2020 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LazZiya/4f64dc7149e3f7f922ee6d32312a4126 to your computer and use it in GitHub Desktop.
Save LazZiya/4f64dc7149e3f7f922ee6d32312a4126 to your computer and use it in GitHub Desktop.
Asp.Net Core XLocalizer sample startup.cs file for Razor Pages localized with XML resource files and online translation.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// ...
public void ConfigureServices(IServiceCollection services)
{
// Configure request localization
services.Configure<RequestLocalizationOptions>(ops =>
{
var cultures = new CultureInfo[] { new CultureInfo("en"), new CultureInfo("tr"), new CultureInfo("ar") };
ops.SupportedCultures = cultures;
ops.SupportedUICultures = cultures;
ops.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en");
ops.RequestCultureProviders.Insert(0, new RouteSegmentRequestCultureProvider(cultures));
});
// Regisgter traslation service
services.AddHttpClient<ITranslator, MyMemoryTranslateService>();
// Register XmlResourceProvider
services.AddSingleton<IXResourceProvider, XmlResourceProvider>();
services.AddRazorPages()
.AddRazorPagesOptions(ops => { ops.Conventions.Insert(0, new RouteTemplateModelConventionRazorPages()); })
// Add XLocalizer
.AddXLocalizer<LocSource, MyMemoryTranslateService>(ops =>
{
ops.ResourcesPath = "LocalizationResources";
ops.AutoAddKeys = true;
ops.AutoTranslate = true;
// Optional: Just in case you need to change the source translation culture.
// if not provided, the default culture will be used
ops.TranslateFromCulture = "en";
// Recommended: turn on caching during production for faster localization
ops.UseExpressMemoryCache = true;
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
// Use request localization middleware
app.UseRequestLocalization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment