[英]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.