初见WCF服务接口

来源:互联网 发布:实况埃芬博格数据 编辑:程序博客网 时间:2024/05/16 08:10

1.建立MVC空项目,

2.创建Service和Service.Interface这两个类库,在Service里创建WCF服务契约(CalculatorService和MyTestService),在Service.Interface里创建IMyTest

3.MVC项目引用:Service和Service.Interface这两个类库


namespace Service
{
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double x, double y);
        [OperationContract]
        double Subtract(double x, double y);
        [OperationContract]
        double Multiply(double x, double y);
        [OperationContract]
        double Divide(double x, double y);
        [OperationContract]
        string ModelTest(string str1,string str2);
    }

    public class CalculatorService : ICalculator
    {
        public double Add(double x, double y)
        {
            return x + y;
        }

        public double Subtract(double x, double y)
        {
            return x - y;
        }

        public double Multiply(double x, double y)
        {
            return x * y;
        }

        public double Divide(double x, double y)
        {
            return x / y;
        }
        public string ModelTest(string str1, string str2)
        {
            string httpRequestMessage = string.Format("{{\"str1\":\"{0}\",\"str2\":\"{1}\"}}", str1, str2);
            return httpRequestMessage;
        }
    }

}

========>>>>>>>>>>>>>>>>>>>>>

namespace Service.Interface
{
    [ServiceContract]
    public interface IMyTest
    {
        [OperationContract]
        double Add(double x, double y);
    }
}


namespace Service
{
    public class MyTestService:IMyTest
    {
        public double Add(double x, double y)
        {
            return (x + y) * 2;
        }
    }
}


4.修改配置文件


  <system.serviceModel>
    <services>
      <service name="Service.CalculatorService" behaviorConfiguration="metadataExchange">
        <endpoint address="" binding="wsHttpBinding" contract="Service.ICalculator"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
      <service name="Service.MyTestService" behaviorConfiguration="metadataExchange">
        <endpoint address="" binding="wsHttpBinding" contract="Service.Interface.IMyTest"/>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metadataExchange">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

5.发布MVC项目


6.手动在发布文件夹根目录下,创建CalculatorService.svc和MyTestService.svc文件,里面只有一句内容:

CalculatorService.svc里:<%@ServiceHost Service="Service.CalculatorService"%>

MyTestService.svc里:<%@ServiceHost Service="Service.MyTestService"%>

7.winform客户端调用服务

7.1:服务引用

测试:http://localhost:8008/MyTestService.svc和localhost:8008/MyTestService.svc

没有问题就可以引用了


7.2:录入服务引用地址,确定




0 0