我正在使用 WCF 和 REST,并且有复杂的类型,但运行良好。现在我需要检查验证,我正在考虑使用 DataAnnotations,例如
public class Customer
{
[Required]
public string FirstName {get;set;}
}
现在的问题是如何将此验证传递给 REST 服务?
另外,我需要在对象返回时对其进行验证,并抛出异常,如果我要抛出异常,那么使用 REST 执行此操作的最佳方法是什么?
我会用验证应用程序块 http://msdn.microsoft.com/en-us/library/dd140088.aspx包含在微软企业库 http://msdn.microsoft.com/en-us/library/dd203099.aspx来验证数据传输对象在服务接口中使用。你可以使用属性通过验证规则来装饰对象的属性 http://msdn.microsoft.com/en-us/library/dd139849.aspx,与ASP.NET 数据注释 http://stephenwalther.com/blog/archive/2008/09/10/asp-net-mvc-tip-43-use-data-annotation-validators.aspx.
如果验证失败,您应该返回适当的 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 入门套件 http://msdn.microsoft.com/en-us/library/ee391967.aspx,你应该抛出一个Web协议异常 http://msdn.microsoft.com/en-us/library/ee391967.aspx,如中所述本文 http://www.robbagby.com/rest/effective-error-handling-with-wcf-rest/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)