【问题标题】:How to Make REST API call in WCF Service?如何在 WCF 服务中调用 REST API?
【发布时间】:2020-02-08 00:48:48
【问题描述】:

我需要实现一个 WCF 服务,该服务在调用时会调用一个 Rest API。 例如。这是服务模型接口

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时使用await。但是为此,我们需要将方法“getresponse”更改为异步,这不起作用,因为定义是从接口 ICalcService 派生的。我尝试在接口中更改相同的方法定义,但又不允许这样做。

这里有什么解决办法?

我想要的是对我的 WCF 服务的简单调用,该服务本身调用一个 REST API,获取结果并返回给被调用者。

谁能提供任何解决方案?

【问题讨论】:

  • 但是你在这里拥有的东西,工作。如果您无法更改方法签名,则必须阻止异步调用,这就是此代码的作用。有什么问题?
  • @CodeCaster 为此,我们需要声明获取响应方法 async ,这是我们无法做到的,因为它直接实现了接口 ICalcService 的定义。当我们将 async 放在接口中的方法定义中时,我们会遇到问题。
  • 您显示的代码不是异步的。它有什么问题?
  • 代码不会这样工作。 Http.GetAsync() 是一个异步方法。
  • 请阅读How to Ask。当很明显它确实有效时,你不能说“不起作用”。除了var foo = await FooAsync(),你也可以说var foo = FooASync().Result;,同步调用它。当然,它有自己的问题。但如果你需要帮助,你必须说明为什么没有。

标签: c# rest wcf


【解决方案1】:

如果您想异步执行该方法,我对您的问题有点困惑。我们必须修改服务合同。

[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();

如果有什么我可以帮忙的,请随时告诉我。

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2020-12-06
    • 1970-01-01
    相关资源
    最近更新 更多