【问题标题】:C# RestSharp RestClient ConfusionC# RestSharp RestClient 混淆
【发布时间】:2021-08-11 11:52:31
【问题描述】:

我正在设置一个我知道可以使用给定凭据的 API 调用。一般来说,我是 C# 和 .NET 的新手,有人告诉我使用 RestSharp 进行 API 调用。什么作为参数传递给 RestClient?我已经尝试过我的本地服务器,但不确定就是这样。

这里是控制器代码:

    const string endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/status";

    string signature;

    using (var sha = SHA256.Create())
    {
        long ts = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds / 1000;
        Console.WriteLine("Timestamp: " + ts);
        var computedHash = sha.ComputeHash(Encoding.UTF8.GetBytes(apiKey + sharedSecret + ts));
        signature = BitConverter.ToString(computedHash).Replace("-", "");
    }

    var client = new RestClient("?");
    var request = new RestRequest(endpoint, Method.GET);

    request.AddHeader("X-Signature", signature);
    request.AddHeader("Api-Key", apiKey);            

    var  response = client.Execute(request);
    Debug.WriteLine("this is the response" + response);

    return View();
}

【问题讨论】:

    标签: c# .net visual-studio


    【解决方案1】:

    端点应该传入RestClient的构造函数。 URL 段应传递到RestRequst

    来自http://restsharp.org/上的示例

    var client = new RestClient("http://example.com");
    // client.Authenticator = new HttpBasicAuthenticator(username, password);
    
    var request = new RestRequest("resource/{id}", Method.POST);
    request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
    request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
    

    因此,在您的示例中,您应该将端点声明为:

    https://api.test.hotelbeds.com/
    

    并将hotel-api/1.0/status 传递给RestRequest 构造函数。

    【讨论】:

    • 好的,我看到了那个例子,不知道为什么我把它复杂化了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 2021-01-26
    • 2011-09-04
    • 2016-03-08
    相关资源
    最近更新 更多