views:

54

answers:

1

With an object like this:

    [DataContract]
    public class SampleItem
    {              
        private int _id;

        [DataMember(IsRequired = true)]
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

        private string _stringValue;

        [DataMember()]
        public string StringValue
        {
            get { return _stringValue; }
            set { _stringValue = value; }
        }

And a REST call like this:

        [WebInvoke(UriTemplate = "", Method = "POST")]        
        public SampleItem Create(SampleItem instance)
        {
            if (instance == null)
                throw new WebFaultException<string>("The SampleItem returned wasn't correctly formatted.",
                                                    HttpStatusCode.BadRequest);               

            return instance;
        }        

If I call it with an invalid SampleItem, say something without an ID like this:

<SampleItem xmlns="http://schemas.datacontract.org/2004/07/UserWebServices" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt;&lt;StringValue&gt;SingleItem&lt;/StringValue&gt;&lt;/SampleItem&gt;

Then the server gives me a 400 (correct) back with no useful error info (all I get is this: The server encountered an error processing the request. See server logs for more details). Ideally I want it to say something like ID is required.

How do I intercept the place where this error is being generated and throw my own WebFaultException?

A: 

Check out the WebProtocolException from the REST Start Kit. You can then send back a custom error message in your exception like this:

catch (Exception ex)
        {
            throw new WebProtocolException(HttpStatusCode.InternalServerError, "Unexpected Error.", new ServiceFault { ExceptionDetail = "Your custom error message here" }, null);
        }
Steve Michelotti
Yeah, thats fine but I have no idea where to catch the deserialization exception because if that gets thrown I never it never reaches the body of Create.
nextgenneo
This only works if you have hosted your service using the the factory from the REST Starter kit doesn't it? The WebServiceHost2Factory. So I think this will not work if you need to host your service using the standard WebServiceHostFactory (for example if you want to make use the of the standard help feature in WCF 4). The Rest Starter kit does include a help feature, but it is not as nice as the one found in WCF 4 (IMO).
Joshua Hayes