title: C# equivalent for PowerShell Invoke-RestMethod -Token
body: <p>I have a PowerShell script that I want to rewrite in C# (initially I wanted to call the PowerShell script from C#, but <a href="https://stackoverflow.com/questions/58954588/run-powershell-script-in-powershell-6-from-c-sharp">here</a> it turned out that rewriting it is propably easier and more elegant).</p>
  
  <p>So this is the PowerShell code I need to port to C#:</p>
  
  <pre><code>$uri = "$BaseUri/auth/token"    
  $bodyJson = ConvertTo-Json @{token = $ApiToken} -Compress
  $response = Invoke-RestMethod `
             -Uri $uri `
             -Method Post `
             -ContentType "application/json" `
             -Body $bodyJson
  $jwtToken = $response.token
  
  #jwtToken is then used to authenticate a GET request:
  $response = Invoke-RestMethod `
             -Uri $uri `
             -Method Get `
             -ContentType "application/json" `
             -Authentication Bearer `
             -Token $jwtToken `
             -AllowUnencryptedAuthentication 
  </code></pre>
  
  <p>This is the C# equivalent I came up with:</p>
  
  <pre><code>//this is only called once
  //ApiToken only has a field called "token", the class only exists for the JSON parser to work
  ApiToken apiToken = new ApiToken();
  client.BaseAddress = new Uri(baseUri);
  client.DefaultRequestHeaders.Accept.Clear();
  client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", apiToken.Token);
  
  //this is called every time
  Task &lt;HttpResponseMessage&gt; postTask = client.PostAsJsonAsync("auth/token", apiToken);   
  HttpResponseMessage response = await postTask;
  jwt = response.???
  </code></pre>
  
  <p>Multiple problems here:</p>
  
  <ol>
  <li>I am new to PowerShell and HttpRequesting and I didn't write the script, so I don't <em>fully</em> understand every little detail here</li>
  <li>I don't know <strong>how to retrieve the JWT returned by the API</strong>, as I can't use <code>response.token</code> in C# (why does that even work in PowerShell? Why does <code>response</code> have a field called token?)</li>
  <li>The C# code returns Error 401 (Unauthorized), while the PowerShell works fine with the same token. My theory is that this happens because I think <strong>I don't send the token correctly</strong>. (I'm not sure if my C# message matches the PowerShell <code>ConvertTo-Json @{token = $ApiToken} -Compress</code>) I feel like I didn't really find the proper equivalent for the <code>-Token</code> parameter that <code>Invoke-RestMethod</code> has.</li>
  </ol>