WCF即微软为构建面向服务的应用程序所提供的统一编程模型。

构建WCF过程:

  1. vs2017,新建一个空白解决方案,新建一个项目WcfDemo,包括一个接口类和一个实现类。再次建立一个控制台应用程序。这里接口类:IUserviceService和实现接口的类:UserInfoService及控制台程序:Host。

  2. 在ServiceDemo中引用System.ServiceModel,在接口类中创建服务契约和操作契约

using System.ServiceModel;
namespace WcfDemo
{
    [ServiceContract]         //服务契约
    public interface IUserInfoService
    {
        [OperationContract]   //操作契约
        int Add(int a, int b);      
    }
}
  1. 在UserInfoService中实现接口IUserInfoService
public class UserInfoService : IUserInfoService
    {
        public int Add(int a, int b)
        {
            return a + b;
        }
    }
  1. 添加控制台ServiceHost的config文件地址;

WCF—服务端创建

4.(1).添加配置文件地址的代码直接复制此代码,只需修改以上两处即可

<!--添加配置文件-->
  <system.serviceModel>
    <services>
      <service name="WcfDemo.UserInfoService" behaviorConfiguration="behaviorConfiguration">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8000/"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="basicHttpBinding" contract="WcfDemo.IUserInfoService"></endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="behaviorConfiguration">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  1. 找到控制台的Program类,引用项目WcfDemo和System.ServiceModel
using System.ServiceModel;
using WcfDemo;

namespace Host
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(UserInfoService)))
            {
                host.Open();
                Console.WriteLine("启动完成");
                Console.ReadKey();
            }
        }
    }

如此图所示,此时Wcf服务端创建完成。
WCF—服务端创建

相关文章:

  • 2021-09-25
  • 2021-06-30
  • 2022-02-02
  • 2022-12-23
  • 2022-01-16
  • 2021-11-04
  • 2021-10-15
  • 2021-09-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
  • 2021-11-29
  • 2021-12-17
  • 2022-01-09
相关资源
相似解决方案