Passing Validation exceptions via WCF REST

前端 未结 2 524
闹比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.

    0 讨论(0)
  • 2021-02-11 04:06

    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.

    0 讨论(0)
提交回复
热议问题