我曾经通过直接添加服务引用来调用接口(C#项目),如下面的示例
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)而不是直接添加服务引用? 有人知道吗?
答案 0 :(得分:0)
由于您正在执行GET
请求,因此参数将放在网址或标题中或两者中。希望文档清楚明了。
//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
(文档真的有吗?这是不负责任的)那么您可能会回到这里询问为什么您的电话永远不会返回。如果您无法在代码库中使用async,请使用HttpWebRequest
而不是HttpClient
等同步API。
如果响应是XML而不是JSON,那么您可以将其读入XDocument
或使用XmlSerializer
将其反序列化为Foo
。我已经尽可能地了解有限的信息,希望这能帮助您实现目标。