【问题标题】:WCF Data Service Error HandlingWCF 数据服务错误处理
【发布时间】:2011-03-02 08:19:20
【问题描述】:

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

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

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

[WebGet] 
public void GenerateException() 
{
    throw new DataServiceException( 403, "Custom Message" );
}

这是我的客户:

WebClient wc = new WebClient(); 
wc.DownloadString(
    new Uri(
      "http://localhost:27820/WcfDataService1.svc/GenerateException"
    )
);

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

有什么想法吗?

非常感谢。

【问题讨论】:

  • 您好,您找到解决问题的方法了吗?我处于完全相同的情况,我什么都没有:/

标签: wcf


【解决方案1】:

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

然后,您可以通过覆盖 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);
        }
    }

【讨论】:

    【解决方案2】:

    您可以使用 WCF FaultContract 属性来抛出和处理业务异常。

    参考LinkExample

    【讨论】:

    • 感谢您找到这个问题,然后发布您的结果。这帮助很大。
    【解决方案3】:

    我使用 Set EntitySetAccessRule to AllRead 解决了我的 403 错误:

             config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 2012-05-13
      • 2017-02-28
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      相关资源
      最近更新 更多