2013-05-16 41 views
0

我正在從我的Silverlight應用程序調用WCF服務方法。 Wcf服務正在返回故障時的故障異常。我能夠從我的WCF服務中拋出異常異常。但它沒有收到我的Silverlight應用程序(.xaml.cs)。相反,我得到一個異常「通訊異常是由用戶未處理,遠程服務器在References.cs文件(自動生成文件)中返回一個錯誤:未找到」 無法捕獲由Silverlight客戶端中的WCF服務拋出的FaultException應用程序

我在我的.Xaml.cs中調用WCF服務方法文件中像下面

 private void btnExecuteQuery_Click(object sender, RoutedEventArgs e) 
     { 
     try 
      { 
      objService.GetDataTableDataAsync(_DATABASENAME, strQuery); 
      objService.GetDataTableDataCompleted += new EventHandler<GetDataTableDataCompletedEventArgs>(objService_GetDataTableDataCompleted); 

      } 
      catch (FaultException<MyFaultException> ex) 
      { 
      lblErrorMessage.Content = "Please Enter a Valid SQL Query"; 
      } 
     } 

And I wrote my GetDataTableDataCompleted event as below 

    void objService_GetDataTableDataCompleted(object sender, GetDataTableDataCompletedEventArgse) 
     { 
     //code 
     } 

這裏是我的服務方法

public IEnumerable<Dictionary<string, object>> GetDataTableData(string dataBaseName, string query) 
    { 
     try 
     { 
      IEnumerable<Dictionary<string, object>> objDictionary; 
      objDictionary = objOptimityDAL.GetDataForSelectQuery(dataBaseName, query); 
      return objDictionary; 
     } 
     catch (Exception ex) 
     { 
      MyFaultException fault = new MyFaultException(); 
      fault.Reason = ex.Message.ToString(); 
      throw new FaultException<MyFaultException>(fault, new FaultReason("Incorrect SQL Query")); 

     } 
    } 

這裏我的WCF服務與數據訪問層進行交互,併成功拋出故障異常,但沒有收到我的客戶方法,而我得到的未處理的異常像 「通信異常是由用戶未處理,則遠程服務器返回錯誤:NOTFOUND」在References.cs代碼如下所示

public System.Collections.ObjectModel.ObservableCollection<System.Collections.Generic.Dictionary<string, object>> EndGetDataTableData(System.IAsyncResult result) { 
      object[] _args = new object[0]; 
      System.Collections.ObjectModel.ObservableCollection<System.Collections.Generic.Dictionary<string, object>> _result = ((System.Collections.ObjectModel.ObservableCollection<System.Collections.Generic.Dictionary<string, object>>)(base.EndInvoke("GetDataTableData", _args, result))); 
      return _result; 
     } 

這裏是WCF的Web.config服務

<?xml version="1.0"?> 
<configuration> 
    <system.web> 
    <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
    <behaviors> 
     <serviceBehaviors>   
     <behavior>   
      <dataContractSerializer maxItemsInObjectGraph="2147483647"/> 
      <serviceMetadata httpGetEnabled="true"/> 
      <serviceDebug includeExceptionDetailInFaults="false"/> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
<system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    </system.webServer> 
</configuration> 

下面是我的ServiceReferences.ClientConfig文件

<configuration> 
    <system.serviceModel> 
    <bindings> 
     <basicHttpBinding> 
     <binding name="BasicHttpBinding_IService1" 
      maxBufferSize="2147483647" 
      maxReceivedMessageSize="2147483647" 
      closeTimeout="01:00:00" 
      receiveTimeout="01:00:00" 
      sendTimeout="01:00:00"> 
      <security mode="None" /> 
     </binding> 
     </basicHttpBinding> 
    </bindings> 
    <client> 
     <endpoint address="http://localhost:3132/Service1.svc" binding="basicHttpBinding" 
      bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1" 
      name="BasicHttpBinding_IService1" /> 
    </client> 
    </system.serviceModel> 
</configuration> 

請建議我好歹趕上的FaultException在我的實verlightClient

由於提前

+1

或許有在配置,因爲你得到通信異常一些錯誤。服務是否可以接到客戶的電話?這聽起來像你試圖調用服務時出現錯誤?也許發佈你的web.configs和完整的堆棧跟蹤? – Jocke

+0

嗨Jocke,感謝您的回覆,我已經使用Config文件編輯了我的文章,並且我能夠成功地調用服務方法,它引發了一個異常,但這裏的問題在於捕獲服務中拋出的異常。 –

+0

你有做[FaultContract](http://msdn.microsoft.com/en-us/library/system.servicemodel.faultcontractattribute(v = vs.95)。aspx)'[FaultContract(typeof(MyFaultException))]'? [您可以閱讀本文](http://msdn.microsoft.com/en-us/library/ee844556(v = vs.95).aspx)以獲取更多詳細信息。 – Tonio

回答

3

你應該選擇的Silverlight啓用WCF服務在您創建服務第一次。它會爲你創建所有的基礎設施。

但您仍然可以手動將必要的代碼添加到WCF服務項目中。

SilverlightFaultBehavior.cs

/// <summary> 
/// The behavior which enables FaultExceptions for Silverlight clients 
/// </summary> 
[AttributeUsage(AttributeTargets.Class)] 
public sealed class SilverlightFaultBehaviorAttribute : Attribute, IServiceBehavior 
{ 
    private class SilverlightFaultEndpointBehavior : IEndpointBehavior 
    { 
     public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) 
     { 
     } 

     public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) 
     { 
     } 

     public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) 
     { 
      endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new SilverlightFaultMessageInspector()); 
     } 

     public void Validate(ServiceEndpoint endpoint) 
     { 
     } 

     private class SilverlightFaultMessageInspector : IDispatchMessageInspector 
     { 
      public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) 
      { 
       return null; 
      } 

      public void BeforeSendReply(ref Message reply, object correlationState) 
      { 
       if ((reply != null) && reply.IsFault) 
       { 
        HttpResponseMessageProperty property = new HttpResponseMessageProperty(); 
        property.StatusCode = HttpStatusCode.OK; 
        reply.Properties[HttpResponseMessageProperty.Name] = property; 
       } 
      } 
     } 
    } 

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) 
    { 
    } 

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
     foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints) 
     { 
      endpoint.Behaviors.Add(new SilverlightFaultEndpointBehavior()); 
     } 
    } 

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
    } 
} 

Service1.cs

[SilverlightFaultBehaviorAttribute] 
public class Service1 : IService1 
{ 
... 
} 

和客戶端上,你應該檢查的回調函數內的e.Error財產。從你的例子嘗試/ catch將無法工作。

Silverlight客戶端

objService.GetDataTableDataCompleted += (s, e) => 
    { 
     if(e.Error != null) { 
      if (e.Error is FaultException) { 
       lblErrorMessage.Content = "Please Enter a Valid SQL Query"; 
      } 
      // do something with other errors 
     } 
     else { 
      // success 
     } 
    }; 

objService.GetDataTableDataAsync(_DATABASEName, strQuery); 
+0

我在按鈕單擊事件中調用objService.GetDataTableDataCompleted事件。那麼你的答案的silverlightclient中的(s,e)參數是什麼,我如何在我的按鈕單擊事件中編寫這個參數。你能不能請你好嗎?我編輯了我的帖子silverlightclient(.xaml.cs),請你仔細閱讀並編輯你的silverlightClient答案。 –

+0

@Sudhakar Byna(s,e)是lambda表達式的輸入參數。您可以在這裏閱讀有關lambda表達式的信息:http://msdn.microsoft.com/en-us/library/bb397687.aspx – vorrtex

+0

謝謝。這次我得到一個未處理的異常,如「System.ServiceModel.FaultException'類型'System.ServiceModel.FaultException'發生在System.ServiceModel.dll中的異常,但未在用戶代碼中處理」在我的服務方法中,同時拋出異常例如 拋出新的FaultException (錯誤,新的FaultReason(「錯誤的SQL查詢」)); –

相關問題