相当于PowerShell Invoke-RestMethod -Token的C# [英] C# equivalent for PowerShell Invoke-RestMethod -Token

查看:328
本文介绍了相当于PowerShell Invoke-RestMethod -Token的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要用C#重写的PowerShell脚本(最初我想从C#调用PowerShell脚本,但是

I have a PowerShell script that I want to rewrite in C# (initially I wanted to call the PowerShell script from C#, but here it turned out that rewriting it is propably easier and more elegant).

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

So this is the PowerShell code I need to port to C#:

$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 the C# equivalent I came up with:

//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有一个名为令牌的字段?)
  3. C#代码返回错误401(未经授权),而PowerShell使用相同的令牌可以正常工作.我的理论是,发生这种情况是因为我认为我没有正确发送令牌. (我不确定我的C#消息是否与PowerShell ConvertTo-Json @{token = $ApiToken} -Compress匹配).我觉得我并没有真正找到与Invoke-RestMethod相同的-Token参数的等效项.
  1. I am new to PowerShell and HttpRequesting and I didn't write the script, so I don't fully understand every little detail here
  2. I don't know how to retrieve the JWT returned by the API, as I can't use response.token in C# (why does that even work in PowerShell? Why does response have a field called token?)
  3. 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 I don't send the token correctly. (I'm not sure if my C# message matches the PowerShell ConvertTo-Json @{token = $ApiToken} -Compress) I feel like I didn't really find the proper equivalent for the -Token parameter that Invoke-RestMethod has.

推荐答案

1)您究竟不了解什么?

1) What precisely do you not understand?

2)它可以在Powershell中工作,因为Invoke-RestMethod反序列化了响应,并且响应中包含一个名为"token"的字段.但是,C#程序希望在编译时知道数据结构.因此,除非您定义它,否则您的程序将不知道它.

2) It works in Powershell because Invoke-RestMethod de-serializes the response and the response contains a field named 'token'. The C# program however wants to know the data structure at compile time. So unless you define it, your program doesn't know about it.

3)如果您正在执行OAuth,则应在AuthenticationHeaderValue中设置"Bearer"

3) If you are doing OAuth, you should be setting "Bearer" in AuthenticationHeaderValue

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

关于请求本身: 我无法在client.PostAsJson()上发表评论,因为我无法在HttpClientExtensions类上找到最新信息,并且我的开发环境也不会自动将其导入.

About the request itself: I can not comment on client.PostAsJson() as I cannot find recent information on the HttpClientExtensions class and my dev environment does not import it automatically either.

但是,这是我上次执行Web请求的方式:

However, here is how I did my last webrequest:

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

Please note that JsonConvert comes from Newtonsoft.Json

这篇关于相当于PowerShell Invoke-RestMethod -Token的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆