1 回答
TA贡献1803条经验 获得超6个赞
您可以将服务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;
//...
}
//...
}
然后,您可以在Startup.cs 中HttpContextAccessor注册转换器时传递该服务ConfigureServices
var httpContextAccessor = new HttpContextAccessor();
services.AddSingleton<IHttpContextAccessor>(httpContextAccessor);
services.AddJsonOptions(options => {
options.SerializerSettings.Converters.Add(new MyJsonConverter(httpContextAccessor));
});
请注意,您不应尝试HttpContext在转换器的构造函数中访问。在写入或读取方法中访问它,因为这很可能在上下文已经填充的请求期间被调用。
- 1 回答
- 0 关注
- 282 浏览
添加回答
举报