Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject/access HttpContext in a JsonConverter?

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.

like image 594
B12Toaster Avatar asked May 21 '18 20:05

B12Toaster


1 Answers

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.

like image 174
Isma Avatar answered Sep 30 '22 10:09

Isma