JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.73k stars 3.25k forks source link

JsonConvert per request context #2871

Open stzach opened 1 year ago

stzach commented 1 year ago

Hello,

I would like to have custom jsonConvert per api request. On each request there is an offset header value and need to deserialise utc datetime using that custom offset value. I have tried to create a JsonConverter or IsoDateTimeConverter but there is no context available there.

Source/destination types

class MyJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var context = serializer.Context;
        ...
    }
}

Expected behavior

I would expect that httpContext would be available.

Actual behavior

context is null.

bartelink commented 1 year ago

Would recommend asking this on stackoverflow.com instead, and closing this one - include more detail as to your overall objective so people can offer a variety of practical solutions.

stzach commented 1 year ago

Thank you bartelink for your response.

So there is nothing related to httpContext in the JsonConverter, right?

bartelink commented 1 year ago

I would be surprised if there is - the library is just that: a library that gets used in an infinite number of contexts. The HttpContext and how it's made available to apps varies over time per HTTP host framework or library, so if the lib was to take a dependency of that kind, it would be a nightmare to test, maintain and document.

Ultimately, the lib is a block of OSS code that you can inspect. If I were you and really wanted to know the answer as to how the context tunnels through in order to make it work, I'd clone the repo, and open it in my IDE. I would not be surprised if you find a test or two that illustrates how it's expected to work too.

The good thing about asking on SO (aside from a large traffic of people who use various web FWs together with the lib (esp when compared to the few watchers of any repo on GH), is that you over time will get multiple answers. The quality of the answer that's possible does depend on you giving as much context as possible to help people answering though.