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
就可以生成客户端需要的契约(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
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com