'WCF Read stream changes the behaviour of a WebFaultException
We have the following web method:
public void RawData(string dataItemName, Stream sourceStream)
{
StreamReader reader = new StreamReader(sourceStream);
{
string data = reader.ReadToEnd();
throw new WebFaultException<string>("error", System.Net.HttpStatusCode.BadRequest);
}
}
and is defined as follows:
[WebInvoke(Method = "POST", UriTemplate= "RawData/{dataItemName}", ResponseFormat = WebMessageFormat.Xml)]
[OperationContract]
[FaultContract(typeof(LoginFaultInfo))]
[FaultContract(typeof(SecurityFaultInfo))]
[FaultContract(typeof(RequestFaultInfo))]
[Description("Sets data for the specified item")]
void RawData(string dataItemName, Stream dataStream);
This correctly generates the exception in the client.
However, if this code is changed as follows:
public void RawData(string dataItemName, Stream sourceStream)
{
using (StreamReader reader = new StreamReader(sourceStream))
{
string data = reader.ReadToEnd();
}
throw new WebFaultException<string>("error", System.Net.HttpStatusCode.BadRequest);
}
Then the client gets a 202 Accepted Status rather than a fault exception.
Does anyone know why this is the case? Reading and disposing of the stream has changed the behaviour somehow,
Solution 1:[1]
Do not use "using" in WCF Client.
You can check Microsoft documentation for instructions.
Close and Abort release resources safely when network connections have dropped
The C# "using" statement results in a call to Dispose(). This is the same as Close(), which may throw exceptions when a network error occurs. Because the call to Dispose() happens implicitly at the closing brace of the "using" block, this source of exceptions is likely to go unnoticed both by people writing the code and reading the code. This represents a potential source of application errors.
I think you can use the Microsoft recommended way of handling WCF client calls.
For more detail see: Expected Exceptions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lan Huang |
