【问题标题】:Call Shopware API from c# with HttpClient使用 HttpClient 从 c# 调用 Shopware API
【发布时间】:2018-06-08 16:00:45
【问题描述】:

我正在尝试从 c# 调用 Shopware REST API。 Shopware 有使用 curl 调用 API 的文档,大多数情况下我可以将其转换为 c# 和 HttpClient,但对于某些选项,我只是不知道要设置哪些标头:

The Shop 支持基本的 htaccess-auth,并使用 apikey 进行 Shopware 身份验证。到目前为止我的代码:

var handler = new System.Net.Http.HttpClientHandler { Credentials = new NetworkCredential(htaccessUsername, htaccessPassword) });
var client = new System.Net.Http.HttpClient(handler);

using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl + "orders?limit=20"))
{
  var encodedStr = Convert.ToBase64String(Encoding.Default.GetBytes($"{username}:{apiKey}"));
  var authorizationKey = "Basic" + " " + encodedStr;
  requestMessage.Headers.Add("Authorization", authorizationKey);
  // curl_setopt($this->cURL, CURLOPT_RETURNTRANSFER, true);
  // curl_setopt($this->cURL, CURLOPT_FOLLOWLOCATION, false);
  // curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
  // curl_setopt(
  //    $this->cURL,
  //    CURLOPT_HTTPHEADER,
  //    ['Content-Type: application/json; charset=utf-8']
  // );
  using (var responseMessage = await client.SendAsync(requestMessage))
  {
    var data = await responseMessage.Content.ReadAsStringAsync();
    System.Diagnostics.Trace.WriteLine(data);
  }
}

基本 htaccess 身份验证正在运行,但 Shopware 身份验证确实失败,并在数据中显示以下响应:

"{\"success\":false,\"message\":\"Invalid or missing auth\"}"

我想我需要以某种方式在 c# 中实现curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);,但我发现不知道如何将这些 curl 选项转换为标题。 有什么帮助吗?

【问题讨论】:

    标签: c# curl httpclient shopware


    【解决方案1】:

    看来你的答案是here

    var credCache = new CredentialCache();
    var basicCred = new NetworkCredential(htaccessUsername, htaccessPassword);
    var digestCred = new NetworkCredential(username, apiKey);
    credCache.Add(new Uri("http://.com/"), "Basic", basicCred);
    credCache.Add(new Uri("http://.com/"), "Digest", digestCred);
    var httpClient = new HttpClient(new HttpClientHandler { Credentials = credCache });
    

    【讨论】:

    • 所以我不再需要requestMessage.Headers.Add("Authorization", authorizationKey); 部分了吗?不错!
    • 老兄,少了点什么,我还是得到"{\"success\":false,\"message\":\"Invalid or missing auth\"}"
    • Funky,当我使用 http 而不是 https 时,我会得到一个 html 错误 401 页面作为结果。
    • 可惜,它看起来不错,但没有帮助。我仍然收到与发送基本凭据时相同的错误。第二个凭据似乎不起作用。
    • 哇,废话 - 根据 Shopware 文档,可能无法同时提交两个凭据:developers.shopware.com/developers-guide/rest-api/faq/…?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    相关资源
    最近更新 更多