积极答复者
WCF中OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader)失败的问题

问题
-
在vs2010中添加了WCF服务的引用后。调用login是获取messageheader。然后使用反射访问GetUserName方法。
代码如下:
class AAA
{
private const string HeaderName = "wcfheader";
private const string HeaderNameSpace = "http://my.wcf.eg";
private static WCFClient lWCFClient = new WCFClient();
private static MessageHeader SessionHeader = null;
public AAA()
{
}static void login(string user,string pwd)
{
using (OperationContextScope lOperationContextScope = new OperationContextScope(lWCFClient.InnerChannel))
{
bool lIsLogIn = false;try
{
lIsLogIn = lWCFClient.login(user, pwd);
if (lIsLogIn)
{
//获取message header
SessionHeader = MessageHeader.CreateHeader(HeaderName, HeaderNameSpace,
OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(HeaderName, HeaderNameSpace));
}
}
catch (FaultException ex)
{
MessageBox.Show("login failed!");
return;
}
}
}//通过反射访问GetUserName方法
static void GetUserNameRef(string user)
{
MethodInfo mf = typeof(WCFClient).GetMethod("GetUserName");
object o = Activator.CreateInstance(typeof(WCFClient));
using (OperationContextScope lOperationContextScope = new OperationContextScope(lWCFClient.InnerChannel))
{
try
{
OperationContext.Current.OutgoingMessageHeaders.Add(SessionHeader);
object rv = mf.Invoke(o, new object[] { user });
}
catch (FaultException ex)
{
Console.WriteLine("logout error!");
}
}
}//直接访问GetUserName方法
static void GetUserName(string user)
{
using (OperationContextScope lOperationContextScope = new OperationContextScope(lWCFClient.InnerChannel))
{
OperationContext.Current.OutgoingMessageHeaders.Add(SessionHeader);
try
{
lWCFClient.GetUserName(user);
}
catch (FaultException ex)
{
Console.WriteLine("GetUserName error!");
}
}
}static void Main(string[] args)
{
login("user001", "user001");GetUserName("user001");//成功GetUserName
GetUserNameRef("user001");//失败:GetUserName error----为什么?怎么处理
}
}请问:
为什么使用反射会访问会失败?如果是因为Invoke方法不是在OperationContext.Current线程中。那么如何处理? 即使用反射也可以正确获取到User Name?
无奈为他- 已编辑 vcinier 2010年6月29日 4:56 abord
全部回复
-
GetUserNameRef("user001");//失败:GetUserName error----为什么?怎么处理
这里报什么错误?
Frank Xu Lei--谦卑若愚,好学若饥
专注于.NET平台下分布式应用系统开发和企业应用系统集成
Focus on Distributed Applications Development and EAI based on .NET
【老徐的网站】:http://www.frankxulei.com/
【老徐的博客】:http://www.cnblogs.com/frank_xl/
【WCF中文技术论坛】:微软WCF中文技术论坛
【WCF英文技术论坛】:微软WCF英文技术论坛 -
各位答谢,小弟已经找到原因了,谢谢。
无奈为他
Frank Xu Lei--谦卑若愚,好学若饥
专注于.NET平台下分布式应用系统开发和企业应用系统集成
Focus on Distributed Applications Development and EAI based on .NET
【老徐的网站】:http://www.frankxulei.com/
【老徐的博客】:http://www.cnblogs.com/frank_xl/
【WCF中文技术论坛】:微软WCF中文技术论坛
【WCF英文技术论坛】:微软WCF英文技术论坛