通常情况下我们关闭一个WCF链接都是简单地写把ICommunicationObject.Close()方法,但是这个方法有个问题就是当调用发生异常时,Close()会发生次生的异常,导致链接不能正常关闭。如果当这种异常很多时,必然对系统的稳定性有很大的影响,所以我们必须要考虑异常发生后如何关闭链接的问题。

我们可以写一个扩展来专门关闭WCF链接,而不是使用原来的Close

        public static void CloseConnection(this ICommunicationObject myServiceClient)
        {
            
if (myServiceClient.State != CommunicationState.Opened)
            {
                
return;
            }
            
try
            {
                myServiceClient.Close();
            }
            
catch (CommunicationException ex)
            {
                Debug.Print(ex.ToString());
                myServiceClient.Abort();
            }
            
catch (TimeoutException ex)
            {
                Debug.Print(ex.ToString());
                myServiceClient.Abort();
            }
            
catch (Exception ex)
            {
                Debug.Print(ex.ToString());
                myServiceClient.Abort();
                
throw;
            }
        }

然后可以使用这个扩展:

        protected void Close(T client)
        {
            
if (client != null)
            {
                IChannel iChannel 
= client as IChannel;
                
if (iChannel != null)
                    iChannel.CloseConnection();
                
else
                {
                    IDisposable iDisposable 
= client as IDisposable;
                    
if (iDisposable != null) iDisposable.Dispose();
                }
            }
        }
posted @ 2009-05-11 17:24 网际飞狐 阅读(328) 评论(0) 编辑

通过往WCF消息头中添加自定义信息,可以用于各种用途,比如可以用于传递AuthKey来判断调用是否合法。

客户端:

            using (OperationContextScope scope = new OperationContextScope(iContextChannel))
            {
                MessageHeader
<string> mh = new MessageHeader<string>("abcde");
                MessageHeader header 
= mh.GetUntypedHeader("AuthKey"http://www.cjb.com/);
                OperationContext.Current.OutgoingMessageHeaders.Add(header);

                
return func();
            }
服务端:
            string authKey = string.Empty;
                
if (OperationContext.Current != null)
                {
                    authKey 
= OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("AuthKey"http://www.cjb.com);
                }
posted @ 2009-05-11 17:22 网际飞狐 阅读(394) 评论(0) 编辑