| | | 1 | | using System.Globalization; |
| | | 2 | | using Kestrun.Hosting; |
| | | 3 | | using Kestrun.Localization; |
| | | 4 | | |
| | | 5 | | namespace Kestrun.Middleware; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Extension methods for adding Kestrun localization middleware. |
| | | 9 | | /// </summary> |
| | | 10 | | public static class KestrunLocalizationMiddlewareExtensions |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Adds Kestrun localization middleware to the pipeline. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <param name="app">The application builder.</param> |
| | | 16 | | /// <param name="options">The localization options.</param> |
| | | 17 | | /// <returns>The application builder.</returns> |
| | | 18 | | public static IApplicationBuilder UseKestrunLocalization( |
| | | 19 | | this IApplicationBuilder app, |
| | | 20 | | KestrunLocalizationOptions options) |
| | | 21 | | { |
| | 8 | 22 | | ArgumentNullException.ThrowIfNull(app); |
| | 8 | 23 | | ArgumentNullException.ThrowIfNull(options); |
| | | 24 | | |
| | 8 | 25 | | var services = app.ApplicationServices; |
| | 8 | 26 | | var env = services.GetService<IHostEnvironment>(); |
| | 8 | 27 | | var contentRoot = env?.ContentRootPath ?? Directory.GetCurrentDirectory(); |
| | | 28 | | |
| | 8 | 29 | | KestrunHost? host = null; |
| | | 30 | | try |
| | | 31 | | { |
| | 8 | 32 | | host = services.GetService<KestrunHost>(); |
| | 8 | 33 | | } |
| | 0 | 34 | | catch |
| | | 35 | | { |
| | | 36 | | // Ignore any errors when host isn't available in this context. |
| | 0 | 37 | | } |
| | | 38 | | |
| | 8 | 39 | | var logger = host?.Logger ?? Serilog.Log.Logger; |
| | 8 | 40 | | var store = new KestrunLocalizationStore(options, contentRoot, logger); |
| | | 41 | | |
| | | 42 | | // Set the default thread culture if specified in options. |
| | 8 | 43 | | if (options.SetDefaultThreadCulture && !string.IsNullOrWhiteSpace(options.DefaultCulture)) |
| | | 44 | | { |
| | | 45 | | try |
| | | 46 | | { |
| | 0 | 47 | | var ci = CultureInfo.GetCultureInfo(options.DefaultCulture); |
| | 0 | 48 | | CultureInfo.DefaultThreadCurrentCulture = ci; |
| | 0 | 49 | | CultureInfo.DefaultThreadCurrentUICulture = ci; |
| | 0 | 50 | | logger.Information("Default thread culture set to {Culture}", ci.Name); |
| | 0 | 51 | | } |
| | 0 | 52 | | catch (CultureNotFoundException) |
| | | 53 | | { |
| | 0 | 54 | | logger.Warning("The specified default culture '{Culture}' is not valid.", options.DefaultCulture); |
| | 0 | 55 | | } |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | // If a KestrunHost is available via DI, capture the store on the host so tools |
| | | 59 | | // and PowerShell helpers can inspect runtime-loaded cultures. |
| | 8 | 60 | | _ = (host?.LocalizationStore = store); |
| | 8 | 61 | | return app.UseMiddleware<KestrunRequestCultureMiddleware>(store, options); |
| | | 62 | | } |
| | | 63 | | } |