关于许多 .Net 版本的信息到处都是,我找不到一个具体的最新示例。
我正在尝试自动修剪我自动发布到 API 的所有“字符串”值。
请注意,这是 ASP.NET CORE 3.x,它引入了新的命名空间“System.Text.Json”等,而不是大多数旧示例使用的 Newtonsoft 命名空间。
Core 3.x 的 API 不使用模型绑定,而是使用 JsonConverter(s)。我正在尝试覆盖它们,因此模型绑定示例在这里不相关。
以下代码确实有效,但这意味着我必须放置注释:
[JsonConverter(typeof(TrimStringConverter))]
在我发布的所有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("{}");
}
.AddJsonOptions
时可以访问的“全局”JsonSerializerOptions中吗?(您必须调用AddControllers或AddMvc / AddMvcCore来链接AddJsonOptions) - pinkfloydx33services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions.Converters.Add(new TrimStringConverter())
的内容。 - pinkfloydx33return reader.GetString()?.Trim();
来防止可能的NullReferenceException
。 - nod