【问题标题】:Trimming all posted strings to an API ASP.NET CORE 3.x将所有发布的字符串修剪为 API ASP.NET CORE 3.x
【发布时间】:2020-12-25 03:12:44
【问题描述】:

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

我正在尝试自动修剪我自动发布到我的 API 的所有“字符串”值。

请注意,这是 ASP.NET CORE 3.x,它引入了新的命名空间“System.Text.Json”等。而不是大多数旧示例正在使用的 Newtonsoft。

Core 3.x API 不使用模型绑定,而是我试图覆盖的 JsonConverter(s),因此模型绑定示例与此处无关。

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

[JsonConverter(typeof(TrimStringConverter))]

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

// TrimStringConverter.cs

// Used https://github.com/dotnet/runtime/blob/81bf79fd9aa75305e55abe2f7e9ef3f60624a3a1/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterString.cs
// as a template From the DotNet source.


using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace User
{
    public class TrimStringConverter : JsonConverter<string?>
    {
        public override string? Read(
            ref Utf8JsonReader reader, 
            Type typeToConvert, 
            JsonSerializerOptions options)
        {
            return reader.GetString().Trim();
        }

        public override void Write(
            Utf8JsonWriter writer, 
            string? value, 
            JsonSerializerOptions options)
        {
            writer.WriteStringValue(value);
        }
    }
}
// CreateUserApiModel.cs

using System.Text.Json.Serialization;

namespace User
{
    public class CreateUserApiModel
    {
        // This one will get trimmed with annotation.
        [JsonConverter(typeof(TrimStringConverter))]
        public string FirstName { get; set; }

        // This one will not.
        public string LastName { get; set; }
    }
}
// ApiController

[HttpPost]
[Route("api/v1/user/create")]
public async Task<IActionResult> CreateUserAsync(CreateUserApiModel createUserApiModel)
{
    // createUserApiModel.FirstName << Will be trimmed.
    // createUserApiModel.LastName, << Wont be trimmed.

    return Ok("{}");
}

【问题讨论】:

  • 是否可以全局注册转换器?
  • 当您在 ConfigureServices 中 .AddJsonOptions 时,您不能将您的转换器添加到您可以访问的“全局”JsonSerializerOptions 吗? (你必须调用 AddControllers 或 AddMvc/AddMvcCore 来链接 AddJsonOptions)
  • 在我的情况下,我猜你的意思是添加选项到 services.AddControllers();在 Startup.cs 中。你有我要添加正确语法的例子吗?
  • 类似于(根据记忆)services.AddControllers().AddJsonOptions(o =&gt; o.JsonSerializerOptions.Converters.Add(new TrimStringConverter())
  • 生病了,看看我能想出什么。

标签: c# asp.net json api asp.net-core


【解决方案1】:

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

// Startup.cs

services.AddControllers()
    .AddJsonOptions(options =>
     {
         options.JsonSerializerOptions.Converters.Add(new TrimStringConverter());
     });

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

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 2022-01-18
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    相关资源
    最近更新 更多