Passing Validation exceptions via WCF REST

2019-03-22 04:45发布

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?

2条回答
何必那么认真
2楼-- · 2019-03-22 05:17

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.

查看更多
ら.Afraid
3楼-- · 2019-03-22 05:42

I would look into writing a custom IDispatchMessageInspector implementation where, in the AfterReceiveRequest method, you manually invoke the validation architecture.

I won't go into the details of how to call the Data Annotations validation architecture as I'm sure you can find that somewhere online if you don't already know how to do it. That said, once you have your validation results you can enumerate them and then, if there are any failed validations, you can throw a generic validation fault filled with the details from the AfterReceiveRequest implementation.

查看更多
登录 后发表回答