张颢镡 发表于 2015-8-12 15:10:27

用IIS Host WCF 简单的5个步骤

  奉上源码
  第一步:定义WCF契约--Contract
  1.新建一个项目(Solutioin),我将其命名为WCFIIS
  2.在项目里添加一个ASP.NET Web Application,命名为WCFService
  3.在WCFService里添加一个接口(Interface),命名为ICalculator。项目结构如下:

  4.添加System.ServiceModel引用,并在ICalculator中引用它

  5.用ServiceContract属性标识ICalculator。添加一个函数Add,用OperationContract属性标识Add,ICalculator如下:

Code
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.ServiceModel;
6
7 namespace WCFService
8 {
9   
10   interface ICalculator
11   {
12         
13         double Add(double a, double b);
14   }
15 }
16   
  第二步:实现(Implement)服务契约
  1.在WCFService中添加一个类,命名为Calculator,并实现接口ICalculator,如下:
  

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WCFService
{
    class Calculator:ICalculator
    {
      #region ICalculator Members

      public double Add(double a, double b)
      {
            return a + b;
      }

      #endregion
    }
}  
  第三步:建立IIS宿主(Host)
  1.在WCFService中添加文件WCFService.svc,内容如下:

< % @ServiceHost Language="C#" Service="WCFService.Calculator" % >  2.在Web.config的<configuration>节点下加入如下配置节:

Code
<system.serviceModel>
<services>
    <service name="WCFService.Calculator" behaviorConfiguration="MyServiceTypeBehaviors">
            <endpoint address=""
            binding="wsHttpBinding"
            contract="WCFService.ICalculator" />
            </service>            
    </services>
    <behaviors>
      <serviceBehaviors>
            <behavior name="MyServiceTypeBehaviors" >
                <serviceMetadata httpGetEnabled="true" />
            </behavior>
            </serviceBehaviors>
      </behaviors>
</system.serviceModel>  3.打开IIS,新建虚拟目录命名为WCFService,并指向WCFService.svc所在目录。
  到此,打开浏览器,输入http://loacalhost/wcfservice/wcfservice.svc,出现如下页面,表示我们的WCF Service建立成功

  
  第四步:建立WCF Client端
  1.新建ASP.NET Web Application,命名为WCFClient
  2.打开Visual Studio Prompt,输入svcutil.exe http://localhost/WCFService/WcfService.svc,结果如下:

  3.将生成的Calculator.cs copy 到WCFClient下。
  第五步:配置并使用Client端
  1.将上一步生成的output.config中<system.serviceModel>节点copy 到WCFClient下Web.config下
  2.并添加System.ServiceModel引用。
  3.在Defalut.aspx.cs的Page_Load中添加如下代码:

CalculatorClient calculatorClient = new CalculatorClient();
double sum = calculatorClient.Add(3.3, 4.4);
Response.Write(sum.ToString());  4.右击Default.aspx,选择View in Browser,结果如下:

  到此,一个用IIS作为Host的简单WCF程序完成。
  奉上源码
页: [1]
查看完整版本: 用IIS Host WCF 简单的5个步骤