2011-01-28 63 views
3

我有一个WCF服务,它引发一个异常,我试图在我的silverlight客户端代码中不恰当地捕获异常。我使用的未申报的故障进行调试的目的,这是我服务的方法:silverlight客户端不明白faultexception

[OperationContract] 
public ServiceResponse MyWCFServiceMethod() 
{ 
    ServiceResponse resp = new ServiceResponse(); 
    //code for setting resp... 

    //purposely throw error here. 
    throw new FaultException(new FaultReason(new FaultReasonText("My fault Reason!")),new FaultCode("my fault code here")); 
    return resp; 
} 
在我的Silverlight客户端视图模型

现在,在服务的回调方法,我尝试来处理这样的:

private void MyServiceCallback(MyWCFServiceMethodCompletedEventArgs e) 
{ 
    if (e.Error == null) 
    { 
     //proceed normally 
    } 
    else if (e.Error is FaultException) 
    { 
     FaultException<ExceptionDetail> fault = e.Error as FaultException<ExceptionDetail>; 
     MessageBox.Show(fault.Detail.Message); 
     MessageBox.Show(fault.Reason.ToString()); 
    } 
} 

在该行else if (e.Error is FaultException)我仍然得到System.Net.WebException {远程服务器返回错误:NOTFOUND}

这些都是配置项

<serviceMetadata httpGetEnabled="true" /> 
<serviceDebug includeExceptionDetailInFaults="true" /> 

这是服务类的声明

[ServiceContract(Namespace = "")] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public class MySilverlightWCFService 
{ 
.... 

这项服务是在同一个Silverlight的解决方案中的另一个项目。 为什么我的silverlight客户端无法获得我抛出的错误异常?

感谢您的时间...

回答

2

服务器可能抛出的是Silverlight是无视一个HTTP 500响应代码。您必须更改服务才能返回Silverlight将接受的HTTP代码。

Data Performance and Fault Strategies in Silverlight 3:(这篇文章将告诉你如何WCF故障返回的Silverlight)

Infamous NotFound Error: When the exception is raised, an HTTP status code of 500 is returned to Silverlight. The browser networking stack prevents Silverlight from reading responses with a status code of 500, so any SOAP fault information contained within is unavailable to the Silverlight client application. Even if the message could be retrieved, Silverlight 2 is not capable of converting the fault back into a managed exception. Both of these issues have been addressed in Silverlight 3.

+0

所以Silverlight的设计没有考虑服务错误处理? :O – user20358 2011-01-30 11:13:27

+0

看起来状态代码必须从500更改为Silverlight可以在服务端读取的内容。那么,如果它是我无法控制的服务呢?我认为这是一个蹩脚的解决方法。要再读一遍,看看我是否错过了一些东西! – user20358 2011-01-30 11:15:59

7

确定,所以最终什么似乎是使这项工作是获得增加一行代码的方式在您抛出异常异常之前,立即向服务提供服务!

System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; 

然后抛出实际的异常:

throw new FaultException(new FaultReason(new FaultReasonText("My fault Reason!")),new FaultCode("my fault code here")); 

然后在Silverlight中修改服务回调错误处理部分从我把我的问题上面:

//else if (e.Error is FaultException) 
    else 
    { 
     //FaultException<ExceptionDetail> fault = e.Error as FaultException<ExceptionDetail>; 
     //MessageBox.Show(fault.Detail.Message); 
     FaultException fault = e.Error as FaultException; 
     MessageBox.Show(fault.Reason.ToString()); 
    } 

这工作为了我。丑陋的方式!

当我得到时间时,我会尝试使用声明的故障。