你可以注入服务
IHttpContextAccessor
转换程序的构造函数。
如下所示:
public class MyJsonConverter : JsonConverter
{
private readonly IHttpContextAccessor httpContextAccessor;
public MyJsonConverter(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var context = httpContextAccessor.HttpContext;
//...
}
//...
}
然后你可以通过
HttpContextAccessor
在中注册转换器时的服务
ConfigureServices
在内部
启动.cs
var httpContextAccessor = new HttpContextAccessor();
services.AddSingleton<IHttpContextAccessor>(httpContextAccessor);
services.AddJsonOptions(options => {
options.SerializerSettings.Converters.Add(new MyJsonConverter(httpContextAccessor));
});
请注意,您不应尝试访问
HttpContext
在转换器的构造函数中。在写入或读取方法中访问它,因为在已经填充了上下文的请求期间很可能会调用该方法。