What could be causing my ISO datetime string with timezone to alter the time during POST request?

When using the fetch API to POST a JSON object as a string to a service method, I encountered an issue with timezones being converted. Initially, the object contained ISO 8601 strings with timezones (e.g. "StartDate": "2019-04-16T13:46:04-06:00"), but upon reaching the C# REST service method ([FromBody]object document), the timezone had changed to "StartDate": "2019-04-16T19:46:04+00:00".

I am puzzled as to why and where this conversion is happening. The data remains as a string throughout the process.

An interesting observation is that this behavior only occurs when deploying the service; everything works as expected when testing locally on localhost.

For reference, please find the example code snippets below:

    postDocument() {
        let doc = "{'StartDate': '2019-04-16T13:46:04-06:00'}";
        let response = await fetch("[serviceURL]/api/Document/AddDocument", 
        {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            body: doc
        });
    }

Server-side code in TestService (C#):

    [HttpPost]
    public void AddDocument([FromBody]object document)
    {
        // Datetime string has already been converted, no longer has timezone.
        console.log(document.ToString()); 
        // startdate here is = "2019-04-16T19:46:04+00:00"
        return;//Doesn't matter what's in this method
    }

Answer №1

By implementing these modifications to the Register function within my WebApiConfig located in App_Start, I was successful in preventing my service from automatically converting the DateTime values, thereby retaining the original timezone information.

public static void Register(HttpConfiguration config)
{
    var jsonFormatter = config.Formatters.JsonFormatter;
    jsonFormatter.SerializerSettings.DateParseHandling = Newtonsoft.Json.DateParseHandling.None;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

C# Error: The SelectCommand.Connection property in Fill has not been initialized, occurring on a single computer

This is the code snippet causing the issue: SqlDataAdapter adapter = new SqlDataAdapter(query, conn); The program runs smoothly on every other computer except the one I am using. On my machine, I encounter the following error: System.InvalidOperatio ...

Is the Prisma model not reachable through Prisma Client?

I'm currently attempting to retrieve a specific property of a Prisma model using Prisma Client. The model in question is related to restaurants and includes a reviews property that also corresponds with a separate Review model. schema.prisma file: // ...

Can anyone recommend a lightweight Ajax Engine that can be developed using C# and ASP.Net? I need something that is adaptable and efficient

Previously, I developed a quick Ajax Framework for a project involving an ASP.Net Website (C#). Since there weren't many Ajax functions required, I created a new blank page and added code to the Page_Load method in the code behind file. This code woul ...

Exploring React Storybook with TaskHarness

I am facing an issue with my React Storybook. The values on the Docs site are not displaying correctly as expected. https://i.sstatic.net/7WBZx.png The expected output should be: https://i.sstatic.net/zl78e.png with updated values. Below is my compone ...

A collection of objects of type T, where T adheres to a specified interface

Is it possible to achieve a similar functionality with this code snippet? public interface ISomeInterface { } public class ClassImplementingISomeInterface: ISomeInterface { } public class AnotherClass { public ICollection<ISomeInterface> SomeProp ...

When a Typescript object contains a key without a corresponding value, what is its significance?

In my experience, I've come across typescript objects that are defined in the following way: const MyObj = { myVar1, name1: myVar2 } Can someone explain the purpose of this object? I know that there is a key-value ...

Verify with introspection whether a particular extension method is being utilized within the function

I've been thinking, what if I have code like this stored in a certain DLL: public class DemoClass { public void TestAction(XMParams command) { var firstName = command.Parse<string>(Params.First, "First Name"); var lastNa ...

managing network delays when using Linq to SQL

My process includes an update thread that runs in the background, using Linq-to-SQL to query the MS SQL Server 2008 R2 DB every 5 minutes for records to update. Occasionally, I encounter an exception: System.Data.SqlClient.SqlException (0x80131904): Con ...

Anticipate receiving a 'Type' returned by external library functions

I've recently started learning TypeScript and have encountered a situation where I need to assign a type to a variable that is returned from a third-party library function with its own type definition. For instance: import {omit} from 'lodash&ap ...

Transform the blob data into an Excel file for easy download, but beware the file is not accessible

My API returns a response containing the content of an excel file, which is displayed in the image below. https://i.sstatic.net/2VHsL.png Now, I am looking to convert this content into an excel file and make it downloadable for the user. Below is the AP ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...

Combine Immer and NgRx reducer for improved state management

Upon analyzing redux and ngrx, it appears that immer is the preferred library for creating a copy of the state before storing it. In following the example provided by immer, I implemented the following code in my reducer: on(exampleActions.updateExample ...

A guide to teaching TypeScript to automatically determine the type of dynamic new() calls

One of the challenges I'm facing involves dynamically creating subclasses and ensuring that the factory function is aware of the subclass's return type. While I can currently achieve this using a cast, I am exploring options to infer the return ...

Specifying the BrowserExecutableLocation in FirefoxOptions while using Selenium does not eliminate the occurrence of an "Unable to find a matching set of capabilities" error

As a newcomer to Selenium, I am experimenting with creating some simple test cases, similar to a "hello world" program. My initial attempt to create an instance of the Firefox Driver looked like this: var options = new FirefoxOptions() { BrowserE ...

How to Send Email with Attachment in c# / ASP.NET without Saving the Attachment

I'm currently facing an issue while attempting to send an email with an attachment that needs to be uploaded by the user and then forwarded to an admin email address. Everything works smoothly on IE 11, but I am experiencing limitations in Chrome/Fir ...

Using TypeScript, you can replace multiple values within a string

Question : var str = "I have a <animal>, a <flower>, and a <car>."; In the above string, I want to replace the placeholders with Tiger, Rose, and BMW. <animal> , <flower> and <car> Please advise on the best approach ...

Is it possible to retrieve a randomized set of the top 10% results from an Angular Material data source?

Sorry for the roughness of the code. It's a work in progress. While I believe it's almost working, I'm struggling to complete it. My goal is to display 10% of the results from an HTTP POST request in a material table. Any tips would be appre ...

What is the best way to implement a SELECT statement in my application that will display multiple values for a certain field, establishing a many-to-many relationship?

It's a bit complicated, but I'll illustrate with an example. Users Table UsedId UserName -------- ---------- 1 Mike 2 Raul HasPrivileges Table UsedId PrivilegeId -------- -------------- 1 1 1 ...

Typescript - Stripping multiple characters from the start and end of a string/Retrieving attributes of a JSON list element

My challenge involves a string like the following : "{"element":"634634"}" My goal is to eliminate {"element":" which remains constant, as well as the final character "}. The only variable component is 634634. How can I achieve this? Alternatively, can ...

Utilizing TypeScript with Vue3 to Pass a Pinia Store as a Prop

My current stack includes Typescript, Pinia, and Vue3. I have a MenuButton component that I want to be able to pass a Pinia store for managing the menu open state and related actions. There are multiple menus in the application, each using the same store f ...