From cabe56abb7e676d81e37d7e8a8d9589450c04a92 Mon Sep 17 00:00:00 2001 From: hello Date: Tue, 9 Apr 2024 07:34:49 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=9C=AC=E5=9C=B0=E5=8C=96?= =?UTF-8?q?=E5=86=85=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- notes/helloshop/localization.md | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/notes/helloshop/localization.md b/notes/helloshop/localization.md index 2c64338..090669a 100644 --- a/notes/helloshop/localization.md +++ b/notes/helloshop/localization.md @@ -1,5 +1,7 @@ # 全球化与本地化 +实现多语言的方法有很多种,可以使用资源文件、数据库、配置文件等方式,本文主要介绍使用资源文件的方式实现多语言,也是微软官方推荐的方式。其它的比如 PO 文件、JSON 文件等也可以实现多语言,但是不如资源文件方便. + ## 创建资源文件 ```text @@ -70,13 +72,10 @@ http://localhost:5000/?culture=en-Us .AspNetCore.Culture=en-US ``` -## OpenApi 设置 Accept-Language +## OpenApi 设置 Accept-Language 以实现多语言 ```csharp -services.AddSwaggerGen(c => -{ - c.OperationFilter(); -}); +services.Configure(options => options.OperationFilter()); ``` ```csharp @@ -84,23 +83,23 @@ public class AcceptLanguageHeaderOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { - if (operation.Parameters == null) + var parameter = new OpenApiParameter { - operation.Parameters = new List(); - } - - operation.Parameters.Add(new OpenApiParameter - { - Name = "Accept-Language", + Name = HeaderNames.AcceptLanguage, In = ParameterLocation.Header, Required = false, Schema = new OpenApiSchema { - Type = "string" + Default = new OpenApiString("zh-CN"), + Type = "string", + Enum = [new OpenApiString("zh-CN"), new OpenApiString("en-US")] } - }); + }; + + operation.Parameters.Add(parameter); } } + ``` ## 实现模型和属性的本地化