关于许多.Net版本的信息到处都是,我找不到一个具体的最新示例。
我正在尝试自动裁剪我发送到API的所有“字符串”值。
注意,这是ASP.NET核心3.x,它引入了新的名称空间“System.Text.Json”等,而不是大多数旧示例使用的Newtonsoft名称空间。
Core3.xAPI不使用模型绑定,而是使用我试图覆盖的JsonConverter,因此模型绑定示例在这里是不相关的。
下面的代码确实可以工作,但这意味着我必须将注释:
[JsonConverter(typeof(TrimStringConverter))]
在我张贴的API模型中的每个字符串之上。我如何做到这一点,以便它只对所有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("{}");
}
发布于 2020-09-08 01:10:36
至于@pinkflowydx33上面的评论,以下内容似乎工作正常。
// Startup.cs
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new TrimStringConverter());
});
另外需要注意的是,任何使用原始问题中的代码的人。除非您添加另一个trim(),否则Converter仅在读取时进行修剪,而不在写入时进行修剪。我只需要一种方式。
https://stackoverflow.com/questions/63765011
复制相似问题