猿问

如何在 JsonConverter 中注入/访问 HttpContext?

在我的 ASP.NET Core 2 应用程序中,每次特定类型的对象被序列化(通过 JSON.NET)时,我想在路径名字符串前面写入当前主机名。

对于此任务,我需要以某种方式将 注入HttpContext到我的自定义JsonConverter 中以获取主机。然而,由于我没有访问HttpContextstartup.cs ConfigureServices(其中转换器注册到MvcJsonOptions),我不知道如何注入HttpContext到我的JsonConverter


江户川乱折腾
浏览 283回答 1
1回答

慕码人8056858

您可以将服务IHttpContextAccessor注入到转换器的构造函数中。类似于以下内容:public class MyJsonConverter : JsonConverter{&nbsp; &nbsp; private readonly IHttpContextAccessor httpContextAccessor;&nbsp; &nbsp; public MyJsonConverter(IHttpContextAccessor httpContextAccessor)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.httpContextAccessor = httpContextAccessor;&nbsp; &nbsp; }&nbsp; &nbsp; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var context = httpContextAccessor.HttpContext;&nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; }&nbsp; &nbsp; //...}然后,您可以在Startup.cs 中HttpContextAccessor注册转换器时传递该服务ConfigureServicesvar httpContextAccessor = new HttpContextAccessor();services.AddSingleton<IHttpContextAccessor>(httpContextAccessor);services.AddJsonOptions(options => {&nbsp; &nbsp; options.SerializerSettings.Converters.Add(new MyJsonConverter(httpContextAccessor));});请注意,您不应尝试HttpContext在转换器的构造函数中访问。在写入或读取方法中访问它,因为这很可能在上下文已经填充的请求期间被调用。
随时随地看视频慕课网APP
我要回答