【问题标题】:How can I translate this three part Curl command to RestSharp?如何将这三部分 Curl 命令转换为 RestSharp?
【发布时间】:2022-07-08 01:57:42
【问题描述】:

我正在尝试使用 API,他们给出的示例是 Curl 命令的形式:

curl --location --request POST 'https://dev-api.itranslate.com/translation/v2/' --header 'Authorization: Bearer 603160b7-cee1-4c13-bcd7-37420b55211d' --header 'Content-Type: application/json' --data-raw '{
    "source": {"dialect": "en", "text": "Hello World"},
    "target": {"dialect": "es"}
}'

我正在尝试使用 RestSharp 复制它。但是,在我能找到的所有 RestSharp 示例中,参数都是整齐的名称-值对。但是在这种情况下,参数是不同的,第一个称为“源”,它由另外两个名称-值对组成。

我试过这样的语法:

request.AddHeader("Authorization", "Bearer 603160b7-cee1-4c13-bcd7-37420b55211d");

request.AddParameter("source", "dialect:'en'");

request.AddParameter("source", "Text:'Hello World'");

request.AddParameter("target", "dialect:'es'");

但是服务器没有响应,我猜是因为它不理解请求。如何将这三个东西(“Source”、“Dialect”和“en”)硬塞到一个名称-值对中?

【问题讨论】:

    标签: curl restsharp


    【解决方案1】:

    您的 curl 请求会发布一个 JSON 对象。但是,您的代码会发布一个 URL 编码形式。

    public record RequestPayload(Source Source, Target Target);
    public record Source(string Dialect, string Text);
    public record Tagret(string Dialect);
    
    
    var client = new RestClient("https://dev-api.itranslate.com/translation/v2/");
    client.UseAuthenticator(new JwtAuthenticator("603160b7-cee1-4c13-bcd7-37420b55211d"));
    var payload = new RequestPayload(new Source("en", "Hello world), new Target("es));
    var request = new RestRequest().AddJsonBody(payload);
    var response = await client.ExecutePostAsync(request);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 2016-10-24
      • 2020-10-21
      • 2015-08-23
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      相关资源
      最近更新 更多