如何使用具有相同wsdl的多个SOAPWeb服务



我正在创建一个服务层,它根据环境使用端点。正在使用ASP.NET Web API 2和C#开发服务层。端点是SOAP,而一个面向测试,而另一个面向生产环境。一个镜像另一个,这就是为什么两者都公开相同的WSDL。由于端点镜像,所以在编译时恰好发生冲突。由于两个代理类具有相同的签名。因此,我的主要问题是如何使我的WEB API服务能够同时使用这两种服务?

在复习了关于这个主题的大部分答案之后。我发现他们之间没有什么共同点。因此,我将分享我的发现和为我工作。

请记住,这两个终点是相同的。我刚刚为我的项目添加了一个服务参考。因此,我只需要一个代理类来解决编译冲突。然而,我仍然必须找到一种方法来改变终点。为此,我在项目web.config文件的appSettings部分添加了三个键。

  <appSettings>        
    <add key="EndPoint" value="TST" />
    <add key="TST" value="http://endpoint_test/Service" />
    <add key="PRD" value="http://endpoint_prod/Service" />
  </appSettings>

EndPoint键值就是我用来选择相应环境的值。

/// <summary>
/// Factory to create proxy classes of a service
/// </summary>
public static class ServiceFactory
{
    /// <summary>
    /// Creates an instance of ServiceClient class from the end-point.
    /// Which stands for the run-time end point hosting the service, such as 
    /// Test or Production, defined in the web.config.
    /// </summary>
    /// <returns>Returns a ServiceClient instance.</returns>
    public static ServiceClient CreateInstance() 
    {
        ServiceClient client = new ServiceClient();
        //getting the end point
        switch (ConfigurationManager.AppSettings["EndPoint"])
        {
            case "TST":
                client.Endpoint.Address = new EndpointAddress("https://endpoint_test/Service");
                break;
            case "PRD":
                client.Endpoint.Address = new EndpointAddress("https://endpoint_prod/Service");
                break;
        }
        return client;
    }
}

然后从控制器调用代理类创建

public class PaymentController : ApiController
{
    public IHttpActionResult Action_X()
    {
        //Getting the proxy class
        ServiceClient client = ServiceFactory.CreateInstance();
       //keep implementing your logic
    }
}

也许这不是最好的实现,但它对我来说很有效。所以我对任何问题和/或建议都持开放态度。

我希望这项工作能为任何需要它的人所用。

最新更新