修剪所有已发布的字符串到 API ASP.NET CORE 3.x

Wil*_*eys 6 c# asp.net api json asp.net-core

有关许多 .Net 版本的信息到处都是,我找不到具体的最新示例。

\n

我正在尝试自动修剪我自动发布到 API\xe2\x80\x99s 的所有 \xe2\x80\x9cstring\xe2\x80\x9d 值。

\n

请注意,这是 ASP.NET CORE 3.x,它引入了新的命名空间 \xe2\x80\x9cSystem.Text.Json\xe2\x80\x9d 等。而不是大多数旧示例使用的 Newtonsoft 命名空间。

\n

Core 3.x API\xe2\x80\x99s 不使用模型绑定,而是使用我尝试覆盖的 JsonConverter,因此模型绑定示例与此处无关。

\n

以下代码确实有效,但这意味着我必须添加注释:

\n
[JsonConverter(typeof(TrimStringConverter))]\n
Run Code Online (Sandbox Code Playgroud)\n

在我也发布的 API 模型中的每个字符串上方。\n我该如何执行此操作,以便它只对全局所有 API 模型中定义为字符串的任何内容执行此操作?

\n
// TrimStringConverter.cs\n\n// Used https://github.com/dotnet/runtime/blob/81bf79fd9aa75305e55abe2f7e9ef3f60624a3a1/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterString.cs\n// as a template From the DotNet source.\n\n\nusing System;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\n\nnamespace User\n{\n    public class TrimStringConverter : JsonConverter<string?>\n    {\n        public override string? Read(\n            ref Utf8JsonReader reader, \n            Type typeToConvert, \n            JsonSerializerOptions options)\n        {\n            return reader.GetString().Trim();\n        }\n\n        public override void Write(\n            Utf8JsonWriter writer, \n            string? value, \n            JsonSerializerOptions options)\n        {\n            writer.WriteStringValue(value);\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
// CreateUserApiModel.cs\n\nusing System.Text.Json.Serialization;\n\nnamespace User\n{\n    public class CreateUserApiModel\n    {\n        // This one will get trimmed with annotation.\n        [JsonConverter(typeof(TrimStringConverter))]\n        public string FirstName { get; set; }\n\n        // This one will not.\n        public string LastName { get; set; }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
// ApiController\n\n[HttpPost]\n[Route("api/v1/user/create")]\npublic async Task<IActionResult> CreateUserAsync(CreateUserApiModel createUserApiModel)\n{\n    // createUserApiModel.FirstName << Will be trimmed.\n    // createUserApiModel.LastName, << Wont be trimmed.\n\n    return Ok("{}");\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Wil*_*eys 8

至于上面 @pinkfloydx33 的评论,以下内容似乎工作正常。

// Startup.cs

services.AddControllers()
    .AddJsonOptions(options =>
     {
         options.JsonSerializerOptions.Converters.Add(new TrimStringConverter());
     });
Run Code Online (Sandbox Code Playgroud)

另请注意,任何人都使用原始问题中的代码。转换器仅在读取时修剪,而不是在写入时修剪,除非您添加另一个修剪()。我只需要一种方式。