我无法让依赖注入在 .NET Core 3.1 中为以下 Newtonsoft JsonConverter 工作。
我只想在属性级别使用它,而不是在全局级别使用它。因此,只有当指定的属性来自某个类时才应执行。
JsonConverter
:
public class HelloWorldCustomConverter : JsonConverter<string>
{
private readonly IMyService _myService;
public HelloWorldCustomConverter(IMyService myService)
{
_myService = myService;
}
public override bool CanRead => false;
public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
{
// append a value using the injected service
writer.WriteValue($"{value}-{myService.GetValue()}");
}
}
Usage:
public class MyClass
{
public string Title { get; set; }
[JsonConverter(typeof(HelloWorldCustomConverter))]
public string Details { get; set; }
}
它是 .NET Core 3.1 和 Newtonsoft.json 版本 13.0.1。
我很感激任何帮助,谢谢。
Edit 1
我从 StackOverflow 检查了很多答案,但到目前为止没有一个对我有用。它们中的大多数都相当过时,或者缺少一些东西来使其正常工作。其中很少有我已经检查过但对我不起作用的:
- 无法替换 ASP.NET Core 3 中的默认 JSON 合约解析器
- .NET Core 中带参数的自定义 JsonConverter
- https://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm
- .Net Core Api - 基于请求值的自定义 JSON 解析器
- http://www.dotnet-programming.com/post/2017/05/07/Aspnet-core-Deserializing-Json-with-Dependency-Injection.aspx
Edit 2
我尝试了建议作为重复参考的帖子,但它在我的情况下不起作用。
- .Net Core Api - 基于请求值的自定义 JSON 解析器
我尝试旋转我的头和各种其他选择,但没有运气。
James 建议的解决方法之一(日期:2108)没有起作用。
Ref: https://github.com/JamesNK/Newtonsoft.Json/issues/1910
你可以尝试类似的东西
public class JsonOptions : IConfigureOptions<MvcJsonOptions>
{
IHttpContextAccessor _accessor;
public JsonOptions(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public virtual void Configure(MvcJsonOptions options)
{
options.SerializerSettings.Converters.Add(new MyCustomConverter(_accessor));
}
}
在您的启动中注册它
services.AddSingleton<IConfigureOptions<MvcJsonOptions>, JsonOptions>()
(不记得 IHttpContextAccessor 是否默认注册,因此您可能还需要注册该访问器)
然后在 Read/WriteJson 方法中使用 _accessor.HttpContext 访问请求的上下文