[asp.net]selfhost wcf

  • 8342
  • 0

[asp.net]selfhost wcf

本文使用visual studio 2017進行,wcf將會在一個console裡面執行

step1:
透過visual studio新增一個空的方案

step2:
新增一個專案,選擇類別庫(.NET Framework),名稱叫做MathService


step3:
在剛才新增的專案裡面,新增一個WCF服務,名稱也叫做MathService


step4:
打開IMathService.cs,定義一個addition function如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace MathService
{
    // 注意: 您可以使用 [重構] 功能表上的 [重新命名] 命令同時變更程式碼和組態檔中的介面名稱 "IMathService"。
    [ServiceContract]
    public interface IMathService
    {
       

        [OperationContract]
        void Addition(int num1, int num2);
    }
}


step5:
打開MathService.cs,實做剛才interface的function如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace MathService
{
    // 注意: 您可以使用 [重構] 功能表上的 [重新命名] 命令同時變更程式碼和組態檔中的類別名稱 "MathService"。
    public class MathService : IMathService
    {
    
        public void Addition(int num1, int num2)
        {
        }
    }
}


step6:
在方案新增一個console應用程式(主控台應用程式(.NET Framework)),名稱叫做MathService_Host


step7:在console專案裡面加入wcf的專案參考


step8:在console專案的program.cs的Main()加入下列內容

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace MathService_Host
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(MathService.MathService));
            host.Open();
            Console.WriteLine("Service Hosted Sucessfully");
            Console.Read();
        }
    }
}


step9:
並且將下列內容加入你的app.config

<?xml version="1.0" encoding="utf-8" ?>  
<configuration>  
	<system.serviceModel>  
		<behaviors>  
			<serviceBehaviors>  
				<behavior name="mexBehaviour">  
					<serviceMetadata httpGetEnabled="true" />  
				</behavior>  
			</serviceBehaviors>  
		</behaviors>  
		<services>  
			<service name="MathService.MathService" behaviorConfiguration="mexBehaviour">  
				<endpoint address="MathService" binding="basicHttpBinding" contract="MathService.IMathService">  
				</endpoint>  
				<endpoint address="MathService" binding="netTcpBinding" contract="MathService.IMathService">  
				</endpoint>  
				<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />  
				<host>  
					<baseAddresses>  
						<add baseAddress="http://localhost:8080/" />  
						<add baseAddress="net.tcp://localhost:8090" />  
					</baseAddresses>  
				</host>  
			</service>  
		</services>  
	</system.serviceModel>  
</configuration>  


step10:
按下F5執行此console,你可以看到此時wcf已經順利啟用了!開網頁http://localhost:8000/也看的到wsdl!!


收工!




參考資料:
Create Simple WCF Service And Host It On Console Application
https://www.c-sharpcorner.com/article/create-simple-wcf-service-and-host-it-on-console-application/