通过WCF REST传递验证异常 [英] Passing Validation exceptions via WCF REST

查看:116
本文介绍了通过WCF REST传递验证异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WCF和REST,并且我有复杂的类型,这是正常工作。现在我需要检查验证,我正在考虑使用DataAnnotations,例如

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

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



此外,我需要在对象验证该对象时抛出异常,如果我要抛出一个异常,那么使用REST最好的方式是什么?

解决方案

我会使用 验证应用程序块 包含在 Microsoft企业库验证数据传输对象正在用于服务界面。您可以使用属性使用验证规则来装饰对象的属性,与 ASP.NET数据注释



如果验证失败,您应该返回一个适当的HTTP错误代码,并包括HTTP响应发生了什么。



这是一个例子:

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

如果(!results.IsValid)
{
string [] errors = results
.Select(r => r.Message)
。 ToArray的();

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

//继续自定义逻辑
}

如果您使用 WCF REST入门工具包,您应该将 WebProtocolException 抛出,作为在这篇文章中描述。


I am using WCF and REST, and I have complex types, which are working fine. Now I need to check for validation, I am thinking of using DataAnnotations e.g.

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

Now where the issue is how do I pass this validation down to the REST service?

ALso I need to validate the object when it comes back, and throw an exception, if I am to throw an exception then what is the best way of doing this using REST?

解决方案

I would use the Validation Application Block included in the Microsoft Enterprise Library to validate the data transfer objects being used in the service interface. You can use attributes to decorate the objects' properties with validation rules, much in the same way as with the ASP.NET Data Annotations.

In case validation fails you should return an appropriate HTTP Error Code and include the details of what went wrong in the HTTP response.

Here is an example:

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
}

If you are using the WCF REST Starter Kit, you should instead throw a WebProtocolException, as described in this article.

这篇关于通过WCF REST传递验证异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆