我曾经通过直接添加服务参考来调用接口(c#project),例如以下示例
ServiceReference1.ExampleClient eClient = new ServiceReference1.ExampleClient();
eClient.GetInfo(ref status,ref count,ref msg);
....
,但是现在他们在ESB注册,我无法直接使用WebService,然后以下示例代码与ESB注册有关
HttpClient client = new HttpClient();
...
//Operations to add headers for client ESB register information
...
HttpResponseMessage response = client.GetAsync(ExampleUrl).Result;
那么,如何使用第二种方法传递参数并调用接口(例如eclent.getinfo),而不是直接添加服务参考?有人知道吗?
由于您正在执行GET
请求,因此参数将在URL或标题或两者兼而有之。希望文档对此很清楚。
//You should share this instance, don't new it up every request
请参阅此
HttpClient client = new HttpClient();
//Craft the URL
string urlWithParams = $"{ExampleUrl}?status={status}&count={count}&msg={msg}";
//Await the response DO NOT USE .Result !
HttpResponseMessage response = await client.GetAsync(urlWithParams);
//Read the response content. I'm assuming it is JSON format so you can read
//it as a string but consult the documentation.
string result = await response.Content.ReadAsStringAsync();
//Now you can deserialize to a class if you need/want to.
//Assume you have a class `Foo` that has properties matching the response JSON.
//And also assuming you have a reference to JSON.Net
Foo theFoo = JsonConvert.DerserializeObject<Foo>(result);
请注意如何将await
用于异步调用。如果您使用.Result
(文档真的有吗?这是不负责任的),那么您可能会回到这里,询问为什么您的电话永远不会返回。如果您无法在代码库中使用异步,则使用HttpWebRequest
的同步API,而不是HttpClient
。
如果响应是XML而不是JSON,则可以将其读取到XDocument
中,或使用XmlSerializer
将其验证为Foo
。我一直在有限的信息中尽我所能,希望这能让您前进。