I18NExtension.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // <author></author>
  2. // <date></date>
  3. // <description></description>
  4. using Microsoft.AspNetCore.Builder;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Localization;
  7. using System.Globalization;
  8. namespace ERP.Framework.Extensions
  9. {
  10. public static class I18NExtension
  11. {
  12. public static void UseI18N(this IApplicationBuilder app)
  13. {
  14. app.UseRequestLocalization(options =>
  15. {
  16. var supporttedCultures = new List<CultureInfo>
  17. {
  18. new CultureInfo("en-US"),
  19. new CultureInfo("zh-CN"),
  20. };
  21. options.DefaultRequestCulture = new RequestCulture("en-US");
  22. options.SupportedCultures = supporttedCultures;
  23. options.SupportedUICultures = supporttedCultures;
  24. options.RequestCultureProviders = new List<IRequestCultureProvider>
  25. {
  26. new LangCultrueProvider(),
  27. };
  28. });
  29. }
  30. }
  31. public class LangCultrueProvider : RequestCultureProvider
  32. {
  33. /// <inheritdoc />
  34. public override Task<ProviderCultureResult?> DetermineProviderCultureResult(HttpContext httpContext)
  35. {
  36. if (httpContext == null)
  37. {
  38. throw new ArgumentNullException(nameof(httpContext));
  39. }
  40. var lang = httpContext.Request.Headers["lang"].ToString();
  41. if (!lang.IsNullOrEmpty())
  42. {
  43. return Task.FromResult<ProviderCultureResult?>(new ProviderCultureResult(lang));
  44. }
  45. return NullProviderCultureResult;
  46. }
  47. }
  48. }