How to create a date header but in the form of ISO 8601

Asked

Viewed 42 times

2

I’m creating a communication with a web api and I needed to create a header date type but formatted to ISO 8601. What I want is to get the following output :

Date: 2017-09-13T08:21:08Z

My code is this::

var tempo = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
var httpWebRequest = (HttpWebRequest)WebRequest.Create("test.com");

What I’ve already tried :

httpWebRequest.Headers.Add("Date", tempo);
httpWebRequest.Headers.Add($"Date: {DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")}");
httpWebRequest.Headers["Date"] = tempo;

With these codes I got the following error :

System.Argumentexception: 'Date header has to be modified with the appropriate property or method.'

2 answers

3


The header should be amended as follows::

httpWebRequest.Date = DateTime.UtcNow;

Take an example here.

0

I have already found a way to solve this problem so I will leave my answer so I can help someone who has the same doubt as me but thanks to those who helped. The answer :

MethodInfo priMethod = httpWebRequest.Headers.GetType().GetMethod("AddWithoutValidate", BindingFlags.Instance | BindingFlags.NonPublic);
priMethod.Invoke(httpWebRequest.Headers, new[] { "Date", tempo });

The output I get is this :

Date: 2017-09-13T08:21:08Z

  • The form it has shown does not perform the output I want but this solution I have found performs the output I wanted, but thank you very much for your help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.