调用 WebRequest 以调用 Web 服务的非常简单的调用就是每次以某种方式进行两次调用,一个没有凭据,一个有?

Very simple call to WebRequest to call a web service is somehow making two calls every time, one without credentials and one with?

我正在用 Key/Password 调用 Shopify 的 API 并且这个非常基本的方法调用每次都以某种方式进行两次调用。我正在使用 "Charles Proxy" 来监听电话,它所做的一切都是双重的,一个有授权,一个没有。

看截图。我做错了什么?

    public string GetJsonReply(string _requestURL)
    {
        string json;

        WebRequest req = WebRequest.Create(_requestURL);
        req.Method = WebRequestMethods.Http.Get;
        req.Credentials = new NetworkCredential(APIKey, Password);

        try
        {
            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
            {
                using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                {
                    json = sr.ReadToEnd();
                }
            }
        }
        catch (Exception e)
        {
            json = e.GetBaseException().ToString();
        }

        return json;
    }

编辑: 方法调用如下:

public IdBillingContract GetBillingAddressInfo(string _id)
{
    string url = "https://myurl.myshopify.com/admin/orders/" + Uri.EscapeDataString(_id) + ".json?fields=id,billing_address";
    return JsonConvert.DeserializeObject<IdBillingContract>(GetJsonReply(url), _serializerSettings);
}

问题是您使用的是 Credentials 属性。不要使用它,因为 .NET 在后台循环尝试不同的身份验证协议,例如 NTLM 等...

public string GetJsonReply(string _requestURL)
{
    string json = string.Empty;
    string apiKey = "Foo";
    string password = "Bar";

    string credentialsFormatted = string.Format("{0}:{1}",apiKey,password);
    byte[] credentialBytes = Encoding.ASCII.GetBytes(credentialsFormatted);
    string basicCredentials = Convert.ToBase64String(credentialBytes);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_requestURL);
    request.Method = WebRequestMethods.Http.Get;

    request.Headers["Authorization"] = "Basic " + basicCredentials;

    try
    {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(responseStream))
        {
            json = reader.ReadToEnd();
        }
    }
    catch (Exception e)
    {
        json = e.GetBaseException().ToString();
    }

   return json;
}