0

Silverlight アプリケーションから WCF サービス メソッドを呼び出しています。Wcf サービスは、失敗時に Fault Exception を返しています。WCF サービスから障害例外をスローできます。しかし、Silverlight アプリケーション (.xaml.cs) を受信して​​いません。代わりに、References.cs ファイル (自動生成ファイル) で「Communication Exception was unhandled by User, the remote server returned an Error:NotFound」という例外が発生します。

以下のように、.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 サービスはデータ アクセス レイヤーと対話し、Fault Exception を正常にスローしていますが、クライアント メソッドを受信して​​いません。代わりに、"Communication Exception was unhandled by User, the remote server returned an Error: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>

私のSilverlightClientでfaultExceptionをキャッチする方法を提案してください

前もって感謝します

4

1 に答える 1

4

初めてサービスを作成したときに、Silverlight Enabled WCF Service を選択する必要があります。それはあなたのためにすべてのインフラストラクチャを作成したでしょう.

ただし、必要なコードを手動で 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、コールバック関数内のプロパティを確認する必要があります。あなたの例のtry/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);
于 2013-05-16T14:55:45.310 に答える