您的位置:首页 > 其它

[WCF]将WCF程序部署在IIS上

2012-08-20 14:01 302 查看
WCF 机制确实不错,虽然谈不上对它有多了解,但仅从应用的角度看,有两个显著:封装通信,契约编程。下面演练一个Demo 来看看如何将 WCF 部署在IIS里头。这个 Demo 服务器提供一个运算服务,客户端根据服务器契约调用该服务,得到结果。

1,新建一个目录(IIS具有访问权限的,所以别在系统目录中创建) IISHostedCalcService,然后在其中新建名为 service.svc 文件,其内容如下:

<%@ServiceHost language=c# Debug="true" Service="Microsoft.ServiceModel.Samples.CalculatorService"%>


这一行声明 ServiceHost 的属性,如开发语言,提供的服务名称等。

2,IISHostedCalcService目录下,新建 App_Code 目录,在 App_Code 下新建名为 Service.cs 文件,其内容如下:

using System;
using System.ServiceModel;

namespace Microsoft.ServiceModel.Samples
{
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}

public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
return n1 + n2;
}
public double Subtract(double n1, double n2)
{
return n1 - n2;
}
public double Multiply(double n1, double n2)
{
return n1 * n2;
}
public double Divide(double n1, double n2)
{
return n1 / n2;
}
}
}


这部分就是前面提到的特点之一:契约编程。在这里,IClculater 就是契约(看到ServiceContract attribute 修饰符了没?),服务器发布这个契约,任何客户端代码都可以使用基于该契约的代码。(不就是接口么?确实算是)。

3,IISHostedCalcService目录下,新建 Web.config 文件,其内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
</behavior>
</serviceBehaviors>
</behaviors>

<services>
<!-- This section is optional with the default configuration
model introduced in .NET Framework 4 -->
<service name="Microsoft.ServiceModel.Samples.CalculatorService" behaviorConfiguration="CalculatorServiceBehavior" >

<!-- This endpoint is exposed at the base address provided by host: http://localhost/servicemodelsamples/service.svc  -->
<endpoint address=""
binding="wsHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />

<!-- The mex endpoint is exposed at http://localhost/servicemodelsamples/service.svc/mex -->
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>

</configuration>


因为 WCF 需要 Host 在IIS上,自然需要进行一些配置,这些配置都放在 Web.config 里头。在运行时,WCF就是根据这些信息构建一个通信终端(endpoint),让客户端可以与之进行通信。

4,至此,服务端代码写完。下面来把这个 WCF 程序部署到 IIS 里面。首先确认你已经安装了.NET 4 和 IIS 7。IIS 7 可以通过如下 installIIS.bat 文件安装(需要以管理员身份运行该 bat),其内容如下:

start /w ocsetup IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-HttpRedirect;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ASP;IIS-CGI;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-ServerSideIncludes;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ODBCLogging;IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;IIS-ClientCertificateMappingAuthentication;IIS-IISCertificateMappingAuthentication;IIS-URLAuthorization;IIS-RequestFiltering;IIS-IPSecurity;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-ManagementScriptingTools;IIS-ManagementService;IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;IIS-LegacyScripts;IIS-LegacySnapIn;IIS-FTPServer;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI;IIS-WebDAV;IIS-FTPSvc;IIS-FTPExtensibility

C:
cd C:\windows\System32\inetsrv

appcmd set config /section:defaultDocument
appcmd add apppool /name:"MyAppPool" /managedPipelineMode:Integrated /managedRuntimeVersion:v4.0

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir


5,进入控制面板->管理工具->Internet 信息服务管理器,右击 Default Web Site ,在弹出菜单中选择添加应用程序,如图所示:(MyAppPool 是.NET 4应用程序池,如果没有请先创建)



6,测试一下,在浏览器中输入:http://localhost/IISHostedCalc/Service.svc,就应该能看到如下提示(注意 yourhost 为你机器的hostname):

CalculatorService 服务

已创建服务。

若要测试此服务,需要创建一个客户端,并将其用于调用该服务。可以使用下列语法,从命令行中使用 svcutil.exe 工具来进行此操作:

svcutil.exe http://yourhost/IISHostedCalc/service.svc?wsdl 这将生成一个配置文件和一个包含客户端类的代码文件。请将这两个文件添加到客户端应用程序,并使用生成的客户端类来调用服务。例如:

C#

class Test
{
static void Main()
{
CalculatorClient client = new CalculatorClient();

// 使用 "client" 变量在服务上调用操作。

// 始终关闭客户端。
client.Close();
}
}

Visual Basic

Class Test
Shared Sub Main()
Dim client As CalculatorClient = New CalculatorClient()
' 使用 "client" 变量在服务上调用操作。

' 始终关闭客户端。
client.Close()
End Sub
End Class


7,至此服务器部署完毕,下面就是按照提示来编写客户端代码了。首先将 C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin 加入到系统变量 PATH 中去(方便在命令行上使用 svcutil 命令)。然后在IISHostedCalcService 目录下新建 client 目录,从命令行进入 client 目录,输入命令:

svcutil http://yourhost/IISHostedCalc/service.svc?wsdl[/code] 
就可以生成客户端需要的契约(CalculatorService.cs)以及与服务器通信所需的配置文件(out.config):

8,编写控制台客户端测试程序。新建C# 控制台程序,修改 Main() 为:

var client = new CalculatorClient();

// 使用 "client" 变量在服务上调用操作。
double i = client.Add(100, 23);

Console.WriteLine(" >> add result {0}", i);

// 始终关闭客户端。
client.Close();

Console.ReadKey();


将 CalculatorService.cs 添加至该工程,将 out.config改名为 app.config添加至该工程,设置 app.config的拷贝策略为 Copy if newer。修改 app.config为(注意 yourhost 为你机器的hostname,与前面的提示页面中出现的一致):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ICalculator" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>

<client>
<endpoint address="http://yourhost/IISHostedCalc/service.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICalculator"
contract="ICalculator" name="WSHttpBinding_ICalculator">
<identity>
<servicePrincipalName value="host/yourhost" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>


9,像工程中添加System.ServiceModel 和 System.ServiceProcess 两个 Reference,编译运行。大功告成,客户端调用服务器端代码,并得到了返回结果:



10,注意将 WCF 部署到 IIS 虽然很方便,但是由于 IIS 的权限非常低,通常是坐不了的。如果要获得较高权限级别的操作(任意写磁盘文件等),可以将 WCF 部署到 window service 中

参考链接:

How to: Host a WCF Service in IIS
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: