In my ASP.NET Core 2 application I want to write the current hostname in front of a pathname string every time an object of a certain type gets serialized (via JSON.NET).
For this task, I need to somehow inject the HttpContext
into my custom JsonConverter to get hold of the host. However, as I do not have access to the HttpContext
within startup.cs ConfigureServices
(where the converter is registered to the MvcJsonOptions
), I don't know how to inject the HttpContext
into my JsonConverter
.
You can inject the service IHttpContextAccessor
into your converter's constructor.
Something like the following:
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;
//...
}
//...
}
You can then pass the HttpContextAccessor
service when registering your converter in ConfigureServices
within Startup.cs
var httpContextAccessor = new HttpContextAccessor();
services.AddSingleton<IHttpContextAccessor>(httpContextAccessor);
services.AddJsonOptions(options => {
options.SerializerSettings.Converters.Add(new MyJsonConverter(httpContextAccessor));
});
Note that you should not try to access the HttpContext
in the constructor of the converter. Access it in either the write or read method as that will most likely be invoked during a request where the context would have already been populated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With