WCF数据服务错误处理

pie*_*980 6 wcf

我已经创建了一个带有服务操作的WCF数据服务.

我想生成一种业务异常.我尝试生成,WebFaultException但我没有看到如何在服务操作抛出此错误时在客户端捕获此错误.

这是我的模拟异常的服务操作:

[WebGet] 
public void GenerateException() 
{
    throw new DataServiceException( 403, "Custom Message" );
}
Run Code Online (Sandbox Code Playgroud)

这是我的客户:

WebClient wc = new WebClient(); 
wc.DownloadString(
    new Uri(
      "http://localhost:27820/WcfDataService1.svc/GenerateException"
    )
);
Run Code Online (Sandbox Code Playgroud)

DownloadString抛出异常,但它只是Internal Server Error,我看不到我的Custom Message.

任何的想法 ?

非常感谢.

jai*_*mie 3

最好抛出DataServiceException。WCF 数据服务运行时知道如何将属性映射到 HTTP 响应,并且始终将其包装在 TargetInitationException

然后,您可以通过重写 DataService 中的 HandleException 来为客户端消费者解压,如下所示:

    /// <summary>
    /// Unpack exceptions to the consumer
    /// </summary>
    /// <param name="args"></param>
    protected override void HandleException(HandleExceptionArgs args)
    {
        if ((args.Exception is TargetInvocationException) && args.Exception.InnerException != null)
        {
            if (args.Exception.InnerException is DataServiceException)
                args.Exception = args.Exception.InnerException as DataServiceException;
            else
                args.Exception = new DataServiceException(400, args.Exception.InnerException.Message);
        }
    }
Run Code Online (Sandbox Code Playgroud)