0

I have an ASP.Net Core 3.1 API with an operation that implements JsonPatch, something like this:

    public async Task<IActionResult> Patch(Guid customerId, [FromBody] JsonPatchDocument<CustomerPatch> request)
{
    
    (...)
    
}

And on Startup I have this, in order to support JsonPatch:

public void ConfigureServices(IServiceCollection services)
    {
        //  (..)
        services.AddControllersWithViews(options =>
        {
            
            var formatter = GetJsonPatchInputFormatter();

            options.InputFormatters.Insert(0, formatter);
        });
    }

    private static NewtonsoftJsonPatchInputFormatter GetJsonPatchInputFormatter()
    {
        var builder = new ServiceCollection()
            .AddLogging()
            .AddMvc()
            .AddNewtonsoftJson()
            .Services.
            BuildServiceProvider();


        var res = builder
           .GetRequiredService<IOptions<MvcOptions>>()
           .Value
           .InputFormatters
           .OfType<NewtonsoftJsonPatchInputFormatter>()
           .First();

        return res;
    }

The thing is that on my CustomerPatch class, I have two properties of type DateTimeOffset, and when I perform a patch with these properties specified with offset, their value arrives Patch method already screwed. Example: if I perform a patch containing 2021-04-27T07:41:40.040-07:41, it gets transformed into 2021-04-27T16:22:40.040, so there seems to be a transformation into DateTime.

After digging for a while I found out that if I change the AddNewtonsoftJson line into the following, it works:

.AddNewtonsoftJson((options) =>
            {
                options.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset;
            })

My question is: is this only applied to JsonPatch, or is this applied to all datetimes on all my project?

Then another question: is there any way of applying this only to the properties I want on the class I want?

user729400
  • 495
  • 7
  • 18
  • 1
    You can see this [thread](https://stackoverflow.com/questions/50628374/json-net-deserializing-datetimeoffset-value-fails-for-datetimeoffset-minvalue-wi) may helpful. – Yinqiu Apr 29 '21 at 01:22
  • Helped in fact. Addes JsonSettings for DateTimeOffset and worked like a charm ;) – user729400 May 06 '21 at 20:27

0 Answers0