Search code examples
c#.netweb-servicesjson.nethttpwebrequest

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


I'm calling Shopify's API with a Key/Password and this very basic method call is somehow making two calls every time. I'm using "Charles Proxy" to snoop the calls and everything it does is double, one with auth and one without.

Look at the screenshots. What am I doing wrong?

    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;
    }

Failed Call

Successful Call

EDIT: The method is invoked like this:

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);
}

Solution

  • The issue is that you're using the Credentials property. Don't use it, because .NET is cycling through in the background attempting the different authentication protocols such as NTLM etc...

    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;
    }