wcf之OperationContextScope

时间:2024-10-18 21:36:44

作用:使用消息头向服务发送额外的信息。

1.客户端代码如下:

 namespace Client
{
class Program
{
static void Main(string[] args)
{
CalculatorClient client = new CalculatorClient("secure");
double n1 = 5.6;
double n2 = 7.3;
double result; result = client.Add(n2, n1);
Console.WriteLine("执行加法后的结果为:{0}", result.ToString()); result = client.Subtract(n2, n1);
Console.WriteLine("执行减法后的结果为:{0}", result.ToString()); result = client.Multiply(n1, n2);
Console.WriteLine("执行乘法后的结果为:{0}", result.ToString()); result = client.Divide(n1, n2);
Console.WriteLine("执行除法后的结果为:{0}", result.ToString()); //CalculatorSessionClient clientSeesion = new CalculatorSessionClient();
//string s = clientSeesion.test("你好我做一个测试!");
//string b = clientSeesion.GetServiceDescriptionInfo();
//Console.WriteLine(s);
//Console.WriteLine(b); Test(); } static void Test()
{
CalculatorSessionClient wcfClient = new CalculatorSessionClient();
try
{
using (OperationContextScope scope = new OperationContextScope(wcfClient.InnerChannel))
{
MessageHeader header
= MessageHeader.CreateHeader(
"Service-Bound-CustomHeader",
"http://Microsoft.WCF.Documentation",
"Custom Happy Value."
);
OperationContext.Current.OutgoingMessageHeaders.Add(header); // Making calls.
Console.WriteLine("Enter the greeting to send: ");
string greeting = Console.ReadLine(); //Console.ReadLine();
header = MessageHeader.CreateHeader(
"Service-Bound-OneWayHeader",
"http://Microsoft.WCF.Documentation",
"Different Happy Value."
);
OperationContext.Current.OutgoingMessageHeaders.Add(header);//TODO:自定义传出消息头的用处? // One-way
wcfClient.test(greeting); // Done with service.
wcfClient.Close();
Console.WriteLine("Done!");
Console.ReadLine();
}
}
catch (TimeoutException timeProblem)
{
Console.WriteLine("The service operation timed out. " + timeProblem.Message);
Console.ReadLine();
wcfClient.Abort();
}
catch (CommunicationException commProblem)
{
Console.WriteLine("There was a communication problem. " + commProblem.Message);
Console.ReadLine();
wcfClient.Abort();
} }
}
}

2.服务端代码:

 namespace Microsoft.ServiceModel.Samples
{
class Program
{
static void Main(string[] args)
{
//创建一个ServiceHost
using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService)))
{
// Open the ServiceHost to create listeners
serviceHost.Open();
Console.WriteLine("服务已经开启!");
Console.WriteLine("按回车键结束服务!");
Console.WriteLine();
Console.ReadLine(); serviceHost.Close(); }
} }
[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);
} [ServiceContract]
public interface ICalculatorSession
{
[OperationContract]
string test(string s); [OperationContract]
string GetServiceDescriptionInfo();
} public class CalculatorService : ICalculator, ICalculatorSession
{
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;
} public string test(string s)
{
Console.WriteLine("Service Said" + s);
WriteHeaders(OperationContext.Current.IncomingMessageHeaders);
return s;
} public string GetServiceDescriptionInfo()
{
StringBuilder sb = new StringBuilder();
OperationContext operationContext = OperationContext.Current;
ServiceHost serviceHost = (ServiceHost)operationContext.Host;
ServiceDescription dec = serviceHost.Description;
sb.Append("Base addresses:\n");
foreach (Uri url in serviceHost.BaseAddresses)
{
sb.Append(" " + url + "\n");
}
sb.Append("Service endpoint:\n");
foreach (ServiceEndpoint endPoint in dec.Endpoints)
{
sb.Append("Address:" + endPoint.Address + "\n");
sb.Append("Binding:" + endPoint.Binding + "\n");
sb.Append("Contract:" + endPoint.Contract + "\n");
} return sb.ToString();
} private void WriteHeaders(MessageHeaders headers)
{
foreach (MessageHeaderInfo header in headers)
{
Console.WriteLine("\t" + header.Actor);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("\t" + header.Name);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\t" + header.Namespace);
Console.WriteLine("\t" + header.Relay);
if (header.IsReferenceParameter == true)
{
Console.WriteLine("IsReferenceParameter header detected: " + header.ToString());
}
}
Console.ResetColor();
}
} }

这个实例演示的是客户端通过OutgoingMessageHeaders添加了一些信息,然后服务端通过IncomingMessageHeaders

附:(也许你会有疑问,事情都是OperationContext做的,要OperationContextScope 干什么:个人理解OperationContextScope 类似于数据库连接对象类,wcfClient.InnerChannel就好像是连接字符串,告诉要连接到哪去,整个OperationContextScope 块就像是数据库中的当期连接,信息头就好像是sql语句,出了OperationContextScope 块范围就好数据库断开了连接,进行其他操作要重新连接,OperationContext 就好像是Command对象执行一些操作)

OperationContextScope 对象建立了当前操作上下文之后,可以使用 OperationContext 执行以下操作:

  • 访问和修改传入和传出消息头和其他属性。

  • 访问运行库,包括调度程序、主机、信道和扩展。

  • 访问其他类型的上下文,如安全、实例和请求上下文。

  • 访问与 OperationContext 对象关联的信道,或(如果信道实现System.ServiceModel.Channels.ISession)访问关联信道的会话标识符。

创建了 OperationContextScope 后,将存储当前的 OperationContext,并且新的 OperationContext 由Current 属性所返回。释放 OperationContextScope 后,将还原原始 OperationContext