Passing Validation exceptions via WCF REST

前端 未结 2 523
闹比i
闹比i 2021-02-11 03:31

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.

publi         


        
2条回答
  •  死守一世寂寞
    2021-02-11 03:47

    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.

提交回复
热议问题