第四章:WCF托管(1)

原文:http://www.wcftutorial.net/Introduction-to-WCF.aspx

IIS 5/6托管

将服务托管在IIS中最大的好处是,当他接受到客户端的第一个请求的时候会自动的启动托管进程。它使用了IIS的众多特性,比如进程回收,空闲关闭,进程健康状态监视和消息驱动。而最大的不足在于,它只支持HTTP协议。

让我们随手做点什么吧,创建一个托管在IIS上的服务。

Step 1:启动VS2008,File->New->Web Site,选择WCF Service并且存放在路径http。这将会直接将服务托管在IIS上,然后选择OK。



Step 2:创建一个HelloWorld的服务,这个服务将会接受一个name作为参数,然后返回Hello name。接口和实现如下所示。

IMyService.cs
[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string HelloWorld(string name);
}


MyService.cs
public class MyService : IMyService
{
    #region IMyService Members
    public string HelloWorld(string name)
    {
        return "Hello " + name;
    }
    #endregion
}


Step 3:Service文件(.svc)包含了服务名称和后台的程序代码。这个文件被用来公布服务。

MyService.svc
<%@ ServiceHost Language="C#" Debug="true" Service="MyService" CodeBehind="~/App_Code/MyService.cs" %>


Step 4:需要在服务端的config文件中进行配置。这里我们只配置了一个wsHttpBinding的终结点,我们还可以配置多个不同绑定协议的终结点。因为我们是托管在IIS中的。我们只能使用Http绑定。在后面的教程中,我们会了解到更多有关于终结点和配置的知识。

Web.Config

<system.serviceModel>
    <services>
        <service behaviorConfiguration="ServiceBehavior" name="MyService">
            <endpoint address="http://localhost/IISHostedService/MyService.svc" binding="wsHttpBinding" contract="IMyService">
                <identity>
                    <dns value="localhost"/>
                </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </service>
    </services>
    <behaviors>
        <serviceBehaviors>
            <behavior name="ServiceBehavior">
                <!-- To avoid disclosing metadata information, 
                set the value below to false and remove the 
                metadata endpoint above before deployment -->
                <serviceMetadata httpGetEnabled="true"/>
                <!-- To receive exception details in faults for 
                debugging purposes, set the value below to true.  
                Set to false before deployment to avoid disclosing exception information -->
                <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>


注意:

你需要在配置文件中配置服务名和服务地址。



当我们运行程序的时候。



Step 5: 我们现在成功的将服务托管在了IIS上,下一步我们在创建客户端应用程序来调用该服务。在创建客户端应用程序之前,我们需要为服务创建代理。这些代理会在客户端程序中使用来与服务进行交互。为了创建代理,运行VS2008命令行工具,使用service工具来创建代理类和它的配置信息。

svcutil  http://localhost/IISHostedService/MyService.svc



Step 6: 现在我们开始创建VS2008客户端的控制台应用程序。



Step 7: 添加System.ServiceModel引用



Step 8: 为代理类创建对象,并且调用HelloWorld方法

static void Main(string[] args)
{
    //Creating Proxy for the MyService 
     MyServiceClient client = new MyServiceClient();
     Console.WriteLine("Client calling the service...");
     Console.WriteLine(client.HelloWorld("Ram"));
     Console.Read();
}


Step 9: 运行该程序,输出如下



我希望你会喜欢将服务托管在IIS上,现在让我们看看如何将程序托管在self-host之上。

猜你喜欢

转载自foreversky12.iteye.com/blog/2306578
今日推荐