1、创建两个类库:
    (1)类库一里面存放服务接口
    (2)类库二里面存放接口实现
    类库一:需要引用using System.ServiceModel;从而能够打特性
    [ServiceContract] [OperationContract]相当于对外暴露的契约

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.ServiceModel;
    5. using System.Text;
    6. using System.Threading.Tasks;
    7. namespace IBLL
    8. {
    9. [ServiceContract]
    10. public interface IUserInfoService
    11. {
    12. [OperationContract]
    13. public int Add();
    14. }
    15. }

    类库二:实现类库一中的接口

    1. using IBLL;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.Text;
    6. using System.Threading.Tasks;
    7. namespace BLL
    8. {
    9. public class UserInfoService : IUserInfoService
    10. {
    11. public int Add()
    12. {
    13. return 10;
    14. }
    15. }
    16. }

    2、创建host控制台程序用来发布

    1. using BLL;
    2. using System;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using System.ServiceModel;
    6. using System.Text;
    7. using System.Threading.Tasks;
    8. namespace Host
    9. {
    10. internal class Program
    11. {
    12. static void Main(string[] args)
    13. {
    14. using (ServiceHost host = new ServiceHost(typeof(UserInfoService)))
    15. {
    16. host.Open();
    17. Console.ReadKey();
    18. }
    19. }
    20. }
    21. }

    在app.config里面配置契约
    配置控制台上的配置:services为节点
    image.png

    1. <?xml version="1.0" encoding="utf-8" ?>
    2. <configuration>
    3. <system.serviceModel>
    4. <services>
    5. <service name="BLL.UserInfoService" behaviorConfiguration="behaviorConfiguration">
    6. <host>
    7. <baseAddresses>
    8. <add baseAddress="http://localhost:8998/"/>
    9. </baseAddresses>
    10. </host>
    11. <endpoint address="" binding="basicHttpBinding" contract="IBLL.IUserInfoService"></endpoint>
    12. </service>
    13. <!--<service name="BLL.UserInfoService" behaviorConfiguration="behaviorConfiguration">
    14. <host>
    15. <baseAddresses>
    16. <add baseAddress="http://localhost:8000/"/>
    17. </baseAddresses>
    18. </host>
    19. <endpoint address="" binding="basicHttpBinding" contract="IBLL.IUserInfoService"></endpoint>
    20. </service>-->
    21. </services>
    22. <behaviors>
    23. <serviceBehaviors>
    24. <behavior name="behaviorConfiguration">
    25. <serviceMetadata httpGetEnabled="true"/>
    26. </behavior>
    27. </serviceBehaviors>
    28. </behaviors>
    29. </system.serviceModel>
    30. </configuration>

    注意可能存在的问题:
    1、运行host文件的时候可能无法添加url到站点
    解决办法:
    管理员运行cmd:
    输入:netsh http add urlacl url=http://+:8998/ user=”\Everyone”