We have a REST API, built with WCF.
We handle all the exceptions backend with WebFaultException like this:
throw new WebFaultException<string>(e.Message, HttpStatusCode.NotAcceptable);
This works just fine except in one scenario where we do a Post, with a stream.
An example of this:
[WebInvoke(Method = "POST", UriTemplate = "saveUser?sessionId={sessionId}&userId={userId}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
[OperationContract]
string SaveUser(string sessionId, int userId, Stream stream);
When handling this stream in a using statement, whenever we then run into an exception we keep getting:
From Fiddler:
HTTP/1.1 400 Bad Request
<p>The server encountered an error processing the request. The exception message is 'The message object has been disposed.'. See server logs for more details. The exception stack trace is: </p>
<p> at System.ServiceModel.Channels.ByteStreamMessage.InternalByteStreamMessage.get_Properties()
at System.ServiceModel.OperationContext.get_IncomingMessageProperties()
at System.ServiceModel.Dispatcher.WebErrorHandler.ProvideFault(Exception error, MessageVersion version, Message& fault)</p>
Looks like it has something to do with the stream and StreamReader being disposed.
I have then tried to remove anything that will dispose the StreamReader, and this acctualy works. The code handling this now looks like this:
This solves the problem with sending correct exception messages, but how bad will this affect our application, not closing or disposing our StreamReader? Do you see any other ways of solving this ?