等效于 PowerShell Invoke-RestMethod -Token 的 C#

C# equivalent for PowerShell Invoke-RestMethod -Token

我有一个要用 C# 重写的 PowerShell 脚本(最初我想从 C# 调用 PowerShell 脚本,但 事实证明重写它可能更容易和更优雅)。

所以这是我需要移植到 C# 的 PowerShell 代码:

$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 

这是我想出的 C# 等价物:

//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 <HttpResponseMessage> postTask = client.PostAsJsonAsync("auth/token", apiToken);   
HttpResponseMessage response = await postTask;
jwt = response.???

这里有多个问题:

  1. 我是 PowerShell 和 HttpRequesting 的新手,我没有编写脚本,所以我没有完全理解这里的每一个细节
  2. 我不知道 如何检索 API 返回的 JWT,因为我不能在 C# 中使用 response.token(为什么甚至可以在 PowerShell 中工作?为什么 response 有一个名为 token 的字段?)
  3. C# 代码 returns 错误 401(未经授权),而 PowerShell 使用相同的标记工作正常。我的理论是,发生这种情况是因为我认为 我没有正确发送令牌 。 (我不确定我的 C# 消息是否与 PowerShell ConvertTo-Json @{token = $ApiToken} -Compress 匹配)我觉得我没有真正找到 Invoke-RestMethod 具有的 -Token 参数的正确等价物。

1) 你到底不明白什么?

2) 它在 Powershell 中有效,因为 Invoke-RestMethod 反序列化响应并且响应包含一个名为 'token' 的字段。然而,C# 程序希望在编译时了解数据结构。所以除非你定义它,否则你的程序不知道它。

3) 如果您正在执行 OAuth,则应在 AuthenticationHeaderValue

中设置 "Bearer"
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Bearer", apiToken.Token);

关于请求本身: 我无法对 client.PostAsJson() 发表评论,因为我找不到有关 HttpClientExtensions class 的最新信息,而且我的开发环境也不会自动导入它。

然而,这是我最后一次网络请求的方式:

var apiToken = new ApiToken()
{
    Token = "mysecret",
};

HttpResponseMessage response = Task<HttpResponseMessage>.Run(async () =>
{
    return await client.PostAsync(
        requestUri: uriEndpoint,
        content: new StringContent(
            content: JsonConvert.SerializeObject(apiToken),
            encoding: Encoding.UTF8,
            mediaType: "application/json"))
    .ConfigureAwait(true);
}).Result;

string fullResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(true);
ApiToken apiResponse = JsonConvert.DeserializeObject<ApiToken>(fullResponse);

请注意 JsonConvert 来自 Newtonsoft.Json