WCF开发工具中有很多比较重要的应用技术及供功能特点需要我们熟练应用。在这里我们将会为大家详细介绍一下有关WCF行为控制的相关内容。希望大家可以从这里介绍的内容中获得相关帮助。#t#
在完成服务契约设计和服务实现后,我们可以设置该服务的运行期行为(Behavior)。这些WCF行为控制包括 Service Behaviors、Endpoint Behaviors、Contract Behaviors、Operation Behaviors。
有关所有行为的说明,可以查看 ms-help://MS.MSSDK.1033/MS.NETFX30SDK.1033/WCF_con/html/5c5450ea-6af1-4b75-a267-613d0ac54707.htm。
以下就常用的行为使用,做些演示。
ServiceBehaviorAttribute & OperationBehaviorAttribute
这是两个最常用的WCF行为控制特性,可用于控制:
服务对象生命周期。
并发管理。
异步通讯。
配置文件参数。
事务。
元数据转换。
会话(Session)周期。
等等...
[ServiceContract]
public interface ICalculate
{
[OperationContract]
int Add(int a, int b);
}
[ServiceBehavior(InstanceContextModeInstanceContextMode=
InstanceContextMode.PerCall)]
public class CalculateService : ICalculate
{
public int Add(int a, int b)
{
Console.WriteLine(this.GetHashCode());
return a + b;
}
}
public class WcfTest
{
public static void Test()
{
AppDomain.CreateDomain("Server").DoCallBack(delegate
{
ServiceHost host = new ServiceHost(typeof(CalculateService));
host.AddServiceEndpoint(typeof(ICalculate), new WSHttpBinding(),
"http://localhost:8080/calc");
host.Open();
});
ChannelFactory<ICalculate> factory = new ChannelFactory
<ICalculate>(new WSHttpBinding(),
"http://localhost:8080/calc");
ICalculate o = factory.CreateChannel();
Console.WriteLine(o.Add(1, 2));
Console.WriteLine(o.Add(1, 2));
factory.Close();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
输出:
30136159
3
41153804
3
ServiceMetadataBehavior
- 1.
- 2.
- 3.
- 4.
- 5.
用于开启元数据获取功能。只有使用该WCF行为控制,客户端才能通过 Svcutil.exe 或其他工具获取服务信息,进而生成客户端代理文件。
ServiceHost host = new ServiceHost(typeof(CalculateService));
host.AddServiceEndpoint(typeof(ICalculate),
new BasicHttpBinding(), "http://localhost:8080/calc");
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = new Uri("http://localhost:8080/calc");
host.Description.Behaviors.Add(behavior);
host.Open();
ServiceDebugBehavior
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
开启调试功能,如将服务器端的异常信息直接传送给客户端。
ServiceHost host = new ServiceHost(typeof(CalculateService));
host.AddServiceEndpoint(typeof(ICalculate),
new WSHttpBinding(), "http://localhost:8080/calc");
host.Description.Behaviors.Find<ServiceDebugBehavior>()
.IncludeExceptionDetailInFaults = true;
host.Open();
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
以上就是对WCF行为控制的相关介绍。