.NET Core開發日志——WCF Client


WCF作為.NET Framework3.0就被引入的用於構建面向服務的框架在眾多項目中發揮着重大作用。時至今日,雖然已有更新的技術可以替代它,但對於那些既存項目或產品,使用新框架重構的代價未必能找到人願意買單。

而在.NET Core平台環境中,WCF也並沒有被完全列入遷移目標。WCF的服務端被擱置一旁,只有客戶端已被移植入.NET Core之中。

這意味着,如果有需求在.NET Core中,尤其是非Windows系統環境,調用現有的WCF服務,也並非一件不可能的事情。

以一個實驗來證明,先建一個解決方案工程,再加入兩個類庫項目及一個控制台應用程序。

WcfService.Contract項目,這是WCF服務的接口,即服務契約。

namespace WcfService.Contract
{
    [ServiceContract]
    public interface ICommunication
    {
        [OperationContract]
        string Ping(string msg);
    }
}

WcfService項目,是對服務的實現。

namespace WcfService
{
    public class Communication : ICommunication
    {
        public string Ping(string msg)
        {
            return string.Format("Pong: {0}", msg);
        }
    }
}

WcfService.Host項目,實現對服務的托管。

namespace WcfService.Host
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var host = new ServiceHost(typeof(Communication)))
            {
                host.AddServiceEndpoint(typeof(ICommunication), new BasicHttpBinding(), new Uri("http://192.168.1.2:6666"));

                host.Open();

                Console.WriteLine("Service is being hosted...");
                Console.Read();
            }
        }
    }
}

以上三個項目皆使用.NET framework 4.5.2作為目標框架。

通過運行WcfService.Host應用程序,可以將WCF服務端啟動起來。當然此服務端只能運行在Windows系統環境之上。(為了實驗,建議將系統的防火牆暫時關閉,以免無法連通)

再找一個非Windows系統的環境,比如我使用的Mac Air。再創建一個控制台應用程序。

dotnet new console -o WcfClientApp

用Visual Studio Code打開工程,建議安裝Nuget Package Manager插件,因為這里需要引入System.ServiceModel.Http類庫。

使用快捷鍵Ctrl(Command)+p,輸入>nuget,選中Nuget Package Manager: Add Package,輸入System.ServiceModel.Http,再選取最新版本的安裝選項,對應的類庫便會自動下載下來。

除了這個類庫之外,還需要使用之前創建的WcfService.Contract的dll文件。將其復制到某個目錄下,並在csproj文件指明其具體位置即可。

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="System.ServiceModel.Http" Version="4.5.3"/>
  </ItemGroup>
  <ItemGroup>
    <Reference Include="WcfService.Contract">
      <HintPath>bin\Debug\netcoreapp2.1\WcfService.Contract.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>

WCF客戶端的代碼如下:

using System;
using System.ServiceModel;
using WcfService.Contract;

namespace WcfClientApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var factory = new ChannelFactory<ICommunication>(
                new BasicHttpBinding(), 
                new EndpointAddress(new Uri("http://192.168.1.2:6666")));
            var channel = factory.CreateChannel();
            Console.WriteLine("Ping...");
            var result = channel.Ping("Hi");
            Console.WriteLine(result);
            ((ICommunicationObject)channel).Close();
            Console.Read();
        }
    }
}

將此客戶端運行起來,可以看到這個實驗成功了。

當然WCF Client在.NET Core上的使用一定是有限制,其僅支持HTTP與TCP兩種通信協議,如NamedPipe(命名管道),MSMQ這種Windows平台特有的通信協議,肯定是不被支持的。不過一般最常用的也就是這兩種,所以大多數應用場景下也是夠用了。

上面提到了WCF服務端不被.NET Core所支持,但如果只是想建一個SOAP的服務,還是有解決方案的。

同樣是在macOS系統上,新建一個Web應用程序。

dotnet new web -o SOAPApp

通過Nuget Package Manager安裝SoapCore類庫,並將WcfService.dll與WcfService.Contract.dll一並引入。

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="wwwroot\"/>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App"/>
    <PackageReference Include="SoapCore" Version="0.9.8.1"/>
  </ItemGroup>
  <ItemGroup>
    <Reference Include="WcfService">
      <HintPath>bin\Debug\netcoreapp2.1\WcfService.dll</HintPath>
    </Reference>
    <Reference Include="WcfService.Contract">
      <HintPath>bin\Debug\netcoreapp2.1\WcfService.Contract.dll</HintPath>
    </Reference>
  </ItemGroup>
</Project>

然后在Startup文件中注入所需的服務,並增加SOAP服務的端點。

namespace SOAPApp
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new Communication());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSoapEndpoint<Communication>("/Communication.svc", new BasicHttpBinding());
        }
    }
}

運行此Web應用程序,注意將默認的local地址改成實際的Url。

再在Windows系統環境下建立一個控制台應用程序作為客戶端用於檢測。

namespace WcfService.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var factory = new ChannelFactory<ICommunication>(new BasicHttpBinding(), 
                new EndpointAddress(new Uri("http://192.168.1.6:5000/Communication.svc")));
            var channel = factory.CreateChannel();
            Console.WriteLine("Ping...");
            var result = channel.Ping("Hi");
            Console.WriteLine(result);
            ((ICommunicationObject)channel).Close();
            Console.Read();
        }
    }
}

運行結果,同樣正常,這次的的嘗試完美結尾。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM