[英]How to Make REST API call in WCF Service?
我需要实现一个 WCF 服务,该服务在被调用时会调用 Rest API。 例如。 这是服务 Model 接口
using System.ServiceModel;
namespace Calc
{
[ServiceContract]
public interface ICalcService
{
[OperationContract]
string getresponse(int id);
}
}
这就是实施
namespace Calc
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class CalcService: ICalcService
{
public string getresponse(int id)
{
//what I want to do is this
HttpClient http = new HttpClient();
string baseUrl = "https://restcountries.eu/rest/v2/name/";
string queryFilter = "?fields=name;capital;currencies";
Console.WriteLine("Enter your country name:");
string searchTerm = Console.ReadLine();
string url = baseUrl + searchTerm + queryFilter;
HttpResponseMessage response = await http.GetAsync(new Uri(url)).Result;
return response.ToString();
}
}
}
我面临的问题是,我们需要在调用 rest API 时使用等待。 但是为此,我们需要将方法“getresponse”更改为异步,因为定义是从接口 ICalcService 派生的,所以这不起作用。 我尝试在接口中更改相同的方法定义,但这又是不允许的。
这里有什么解决方案?
我想要的是对我的 WCF 服务的简单调用,该服务本身调用 REST API,获取结果并返回给被调用者。
任何人都可以提供任何解决方案吗?
如果您想异步执行该方法,我对您的问题有点困惑。 我们必须修改服务合同。
[OperationContract]
Task<string> GetResponse(int id);
public async Task<string> GetResponse(int id)
{
Task<string> task = new Task<string>(() =>
{
Thread.Sleep(1000);
return "Hello";
});
task.Start();
return await task;
}
如果我们想同步执行该方法,就像您一样。
HttpResponseMessage response = await http.GetAsync(new Uri(url)).Result;
return response.ToString();
如果有什么我可以帮忙的,请随时告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.