【问题标题】:Passing Validation exceptions via WCF REST通过 WCF REST 传递验证异常
【发布时间】:2011-01-30 21:46:31
【问题描述】:

我正在使用 WCF 和 REST,并且我有复杂的类型,它们运行良好。现在我需要检查验证,我正在考虑使用 DataAnnotations,例如

public class Customer
{
   [Required]
   public string FirstName {get;set;}
}

现在的问题是如何将此验证传递给 REST 服务?

我还需要在对象返回时对其进行验证并抛出异常,如果我要抛出异常,那么使用 REST 执行此操作的最佳方法是什么?

【问题讨论】:

  • 你的意思是来自 ASP.NET MVC 的数据注解 API 吗??

标签: wcf validation rest exception


【解决方案1】:

我会使用Microsoft Enterprise Library 中包含的Validation Application Block 来验证服务接口中使用的数据传输对象。您可以use attributes to decorate the objects' properties with validation rules,与ASP.NET Data Annotations 的方式大致相同。

如果验证失败,您应该返回适​​当的 HTTP 错误代码,并在 HTTP 响应中包含错误的详细信息。

这是一个例子:

public void PostCustomer(Customer instance)
{
    ValidationResults results = Validation.Validate(instance);

    if (!results.IsValid)
    {
        string[] errors = results
            .Select(r => r.Message)
            .ToArray();

        WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadRequest;
        WebOperationContext.Current.OutgoingResponse.StatusDescription = String.Concat(errors);
    }

    // Proceed with custom logic
}

如果您使用的是WCF REST Starter Kit,则应改为抛出WebProtocolException,如this article 中所述。

【讨论】:

    【解决方案2】:

    我会考虑编写一个自定义的IDispatchMessageInspector 实现,在AfterReceiveRequest 方法中,您可以手动调用验证架构。

    我不会详细介绍如何调用 Data Annotations 验证架构,因为如果您还不知道如何调用,我相信您可以在网上的某个地方找到它。也就是说,一旦您获得了验证结果,您就可以枚举它们,然后,如果有任何验证失败,您可以抛出一个通用验证错误,其中填充了 AfterReceiveRequest 实现中的详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      相关资源
      最近更新 更多