就其ClientBase
本身而言,没有地方可以获取该信息。但是您可以在客户端 ( ) 添加一个自定义消息检查IClientMessageInspector
器,您可以在其中查看所有正在接收的消息;对于这些消息,您可以检查IsFault
属性,如果为真,则根据需要记录消息。
更新:添加示例代码
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
public class StackOverflow_12842014
{
[ServiceContract]
public interface ITest
{
[OperationContract]
string Echo(string text);
}
public class Service : ITest
{
public string Echo(string text)
{
if (text == "throw") throw new ArgumentException("Throwing as requested");
return text;
}
}
class MyClient : ClientBase<ITest>, ITest
{
public MyClient(Binding binding, EndpointAddress address)
: base(binding, address)
{
this.Endpoint.Behaviors.Add(new MyFaultLogger());
}
public string Echo(string text)
{
return this.Channel.Echo(text);
}
class MyFaultLogger : IEndpointBehavior, IClientMessageInspector
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(this);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
if (reply.IsFault)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Fault received!: {0}", reply);
Console.ResetColor();
}
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
return null;
}
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");
MyClient client = new MyClient(new BasicHttpBinding(), new EndpointAddress(baseAddress));
Console.WriteLine(client.Echo("Hello"));
try
{
Console.WriteLine(client.Echo("throw"));
}
catch (Exception)
{
Console.WriteLine("The fault should have been traced");
}
client.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}