LocalizationServiceCollectionExtensions.cs
2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using NCC;
using NCC.Dependency;
using NCC.Localization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.Razor;
using System;
using System.Text.Encodings.Web;
using System.Text.Unicode;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// 多语言服务拓展类
/// </summary>
[SuppressSniffer]
public static class LocalizationServiceCollectionExtensions
{
/// <summary>
/// 配置多语言服务
/// </summary>
/// <param name="mvcBuilde"></param>
/// <returns></returns>
public static IMvcBuilder AddAppLocalization(this IMvcBuilder mvcBuilde)
{
var services = mvcBuilde.Services;
// 添加多语言配置选项
services.AddConfigurableOptions<LocalizationSettingsOptions>();
// 获取多语言配置选项
var localizationSettings = App.GetConfig<LocalizationSettingsOptions>("LocalizationSettings", true);
// 如果没有配置多语言选项,则不注册服务
if (localizationSettings.SupportedCultures == null || localizationSettings.SupportedCultures.Length == 0) return mvcBuilde;
// 注册多语言服务
services.AddLocalization(options =>
{
if (!string.IsNullOrWhiteSpace(localizationSettings.ResourcesPath))
options.ResourcesPath = localizationSettings.ResourcesPath;
});
// 配置视图多语言和验证多语言
mvcBuilde.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(localizationSettings.LanguageFilePrefix, localizationSettings.AssemblyName);
});
// 注册请求多语言配置选项
services.Configure((Action<RequestLocalizationOptions>)(options =>
{
Penetrates.SetRequestLocalization(options, localizationSettings);
}));
// 处理多语言在 Razor 视图中文乱码问题
services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
return mvcBuilde;
}
}
}