如何从桌面c#app中使用Web服务?

时间:2014-11-14 17:38:46

标签: web-services xml-serialization datacontractserializer

我正在尝试使用HTTP Web服务返回由C#Desktop应用程序中的DataContractSerializer生成的XML。该服务的链接没有任何aspx或svc扩展,并且链接中需要参数。

https://sourcesite.com/api/external/v1/Snapshot?isConfirmed= {isConfirmed}&安培; sinceDate = {sinceDate}&安培; PAGENUMBER = {PAGENUMBER}&安培; recordsPerPage = {recordsPerPage}

当我在浏览器中使用它时(在提供适当的参数值之后)它可以工作。当它第一次运行时,它询问了我接受的凭据,并且即使在浏览器重启后也没有再询问。

我尝试添加网络参考(使用VS2013),使用没有参数的网址但我收到错误:

The remote server returned an unexpected response: (405) Method Not Allowed.

如果我添加硬编码参数,我会得到:

The document at the url https://sourcesite.com/api/external/v1/Snapshot?isConfirmed=True was not recognized as a known document type. The error message from each known type may help you fix the problem: - Report from 'XML Schema' is 'Data at the root level is invalid. Line 1, position 1.'. - Report from 'DISCO Document' is 'Data at the root level is invalid. Line 1, position 1.'. - Report from 'WSDL Document' is 'There is an error in XML document (1, 1).'. - Data at the root level is invalid. Line 1, position 1. Metadata contains a reference that cannot be resolved: 'https://sourcesite.com/api/external/v1/Snapshot?isConfirmed=True'. The remote server returned an unexpected response: (405) Method Not Allowed. The remote server returned an error: (405) Method Not Allowed. If the service is defined in the current solution, try building the solution and adding the service reference again.

服务配置错误,或者我遗失了什么?也许有一种不同的方式从代码连接到这个服务?

2 个答案:

答案 0 :(得分:0)

“添加服务引用”和“添加Web引用”适用于SOAP Web服务。

您必须使用WebClient课程并“自己动手”。

答案 1 :(得分:0)

我终于让它工作了:

        var netCred = new NetworkCredential { UserName = "user1", Password = @"pass1" };
        WebClient proxy = new WebClient();
        proxy.Credentials = netCred;

        //Method 1 - Newtonsoft.Json


            string serviceURL =
               string.Format("https://sourcesite.com.com/api/external/v1/Snapshot-Accrual?isConfirmed="
                + Confirmed.ToString() + "&sinceDate=" + String.Format("{0:yyyy-MM-dd}", SinceDate);
            data = proxy.DownloadData(serviceURL);
            jsonString = Encoding.ASCII.GetString(data);

            ac1 = Newtonsoft.Json.JsonConvert.DeserializeObject<SnapshotAccruals>(jsonString);

现在如果我只知道如何提示凭证而不是硬编码,我就会被设置。我知道如果我将serviceURL直接粘贴到浏览器中,它会询问我的凭据。如果我在代码中省略它们(401)未经授权。

相关问题