C# 客户端动态调用WCF服务

zhang135956731 2011-06-16 04:59:56
不使用添加服务引用的方法!


客户端方法:
public static object ExecuteMethod<ICalculator>(string pUrl, string pMethodName, params object[] pParams)
{
EndpointAddress address = new EndpointAddress(pUrl);
Binding bindinginstance = null;
//NetTcpBinding ws = new NetTcpBinding();
WSHttpBinding ws = new WSHttpBinding();
ws.MaxReceivedMessageSize = 20971520;
ws.Security.Mode = SecurityMode.None;
bindinginstance = ws;
using (ChannelFactory<ICalculator> channel = new ChannelFactory<ICalculator>(bindinginstance, address))
{
ICalculator instance = channel.CreateChannel();
using (instance as IDisposable)
{
try
{
Type type = typeof(ICalculator);
MethodInfo mi = type.GetMethod(pMethodName);
return mi.Invoke(instance, pParams);
}
catch (TimeoutException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (CommunicationException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (Exception vErr)
{
(instance as ICommunicationObject).Abort();
throw;
}
}
}
}

服务端config配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehaver">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://192.168.1.106:9999/calculatorservice/metadata"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="metadataBehaver" name="Service.CalculatorService" >
<endpoint address="http://192.168.1.106:9999/calculatorservice/metadata" binding="wsHttpBinding" contract="Contract.ICalculator"/>
</service>
</services>
</system.serviceModel>
</configuration>

客户端调用如下:
private void btnResult_Click(object sender, EventArgs e)
{
lblResult.Text = dongtaisecond.ExecuteMethod<ICalculator>("http://192.168.1.106:9999/calculatorservice/metadata", "add", new object[] { double.Parse(txtFirstNum.Text.Trim()), double.Parse(txtSecondNum.Text.Trim()) }).ToString();
}


这个方法不需要使用添加Web服务引用,故应该也不用添加客户端config配置文件了吧?
先启动服务,然后运行客户端程序,服务可以正常启动,客户端程序运行时报错,错误如下:

未处理 System.Reflection.TargetInvocationException
Message="调用的目标发生了异常。"
Source="mscorlib"
StackTrace:
在 System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
在 System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
在 System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
在 Client.dongtaisecond.ExecuteMethod[ICalculator](String pUrl, String pMethodName, Object[] pParams) 位置 E:\张志强\练习\WcfService(动态调用)\Client\dongtaisecond.cs:行号 46
在 Client.Form1.btnResult_Click(Object sender, EventArgs e) 位置 E:\练习\WcfService(动态调用)\Client\Form1.cs:行号 33
在 System.Windows.Forms.Control.OnClick(EventArgs e)
在 System.Windows.Forms.Button.OnClick(EventArgs e)
在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
在 System.Windows.Forms.Control.WndProc(Message& m)
在 System.Windows.Forms.ButtonBase.WndProc(Message& m)
在 System.Windows.Forms.Button.WndProc(Message& m)
在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
在 System.Windows.Forms.Application.Run(Form mainForm)
在 Client.Program.Main() 位置 E:\练习\WcfService(动态调用)\Client\Program.cs:行号 18
在 System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Threading.ThreadHelper.ThreadStart()
InnerException: System.ServiceModel.FaultException
Message="无法处理消息。这很可能是因为操作“http://192.168.1.106:9999/calculatorservice/metadata/CalculatorService/add”不正确,或因为消息包含无效或过期的安全上下文令牌,或因为绑定之间出现不匹配。如果由于未处于活动状态导致服务中止了该通道,则安全上下文令牌无效。若要防止服务永久中止闲置会话,请增加服务终结点绑定上的接收超时。"
Source="mscorlib"
StackTrace:
Server stack trace:
在 System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
在 System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
在 System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
在 System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
在 System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
在 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
在 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
在 Contract.ICalculator.add(Double x, Double y)
InnerException:

整体就是这样的,还请高手指点,感激不尽!谢谢!如果有好的方法也可以直接贴出来,可以的话 尽量详细点 小弟新手 谢谢了。。。
...全文
1299 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
asdasdwdzxczxczxc 2012-06-29
  • 打赏
  • 举报
回复
现在解决了吗。我也遇到这个问题。动态调用??

110,500

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧