0

我正在从我的 Silverlight 应用程序调用 WCF 服务方法。Wcf 服务在失败时返回错误异常。我能够从我的 WCF 服务中抛出错误异常。但它没有收到我的 Silverlight 应用程序 (.xaml.cs)。相反,我在 References.cs 文件(自动生成文件)中收到异常“通信异常未被用户处理,远程服务器返回错误:未找到”

我在我的 .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 服务正在与数据访问层交互并成功抛出故障异常,但它没有接收到我的客户端方法,而是收到未处理的异常,例如“用户未处理通信异常,远程服务器返回错误:未找到" 在 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 的 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)
    {
    }
}

服务1.cs

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

在客户端上,您应该检查e.Error回调函数中的属性。从您的示例中尝试/捕获将不起作用。

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 回答