如何通过ESB方式调用Web服务接口

时间:2017-12-26 09:48:23

标签: c# web-services

我曾经通过直接添加服务引用来调用接口(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)而不是直接添加服务引用? 有人知道吗?

1 个答案:

答案 0 :(得分:0)

由于您正在执行GET请求,因此参数将放在网址或标题中或两者中。希望文档清楚明了。

//You should share this instance, don't new it up every request

see this

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。我已经尽可能地了解有限的信息,希望这能帮助您实现目标。