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

标签 c# .net web-services json.net httpwebrequest

我正在使用 key /密码调用 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;
    }

Failed Call

Successful Call

编辑:该方法是这样调用的:

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 在后台循环尝试不同的身份验证协议(protocol),例如 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;
}

关于c# - 调用 WebRequest 以调用 Web 服务的非常简单的调用就是每次以某种方式进行两次调用,一个没有凭据,一个有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35564216/

相关文章:

web-services - 此Web服务安全方案有哪些潜在问题?

c# - 如何在DataContext类中公开DataContext?

c# - Thread.Abort() 什么时候不会真正中止?

c# - 如何删除DataGridView中特定链接单元格的下划线

c# - EnumMemberAttribute 值被 DataContractJsonSerializer 忽略

java - tomcat作为windows中的服务不加载设备的dll文件

c# - EF LINQ to SQL,除以零错误,生成的查询将参数置于错误的顺序

c# - mef - 如何自动进行重组?

c# - 如何将图片插入到excel单元格中?

java - 如何在本地主机上启动 cxf 服务但在 wsdl 中返回外部地址?