异常数据协定代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel ;
using System.Runtime.Serialization;
namespace Contracts
{
[DataContract]
public class MyError
{
private string co
[DataMember]
public string Co
{
get { return co
set { co
}
private string message = "";
[DataMember]
public string Message
{
get { return message; }
set { message = value; }
}
}
}
在服务协定中使用co
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Contracts
{
[ServiceContract(SessionMode=SessionMode.Required)]
public interface ISession
{
//注意:不能用单工(IsOneWay=false)
[OperationContract(IsOneWay=false,IsInitiating=true,IsTerminating=false )]
[FaultContract(typeof(MyError))]
void Adds(double d);
[OperationContract(IsInitiating=false,IsTerminating=true)]
double GetResult();
}
}
服务协定的实现Co
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Contracts;
namespace Services
{
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
public class CSession:ISession
{
private double result = 0;
#region ISession 成员
public void Adds(double d)
{
MyError myerr = new MyError();
myerr.Co
myerr.Message = "这是一个错误";
FaultException<MyError> err = new FaultException<MyError>(myerr);
throw err;
this.result+=d;
System.Console.WriteLine("Adds{0}",d);
}
public double GetResult()
{
Console.WriteLine("The GetResult method is invoked and the current session ID is: {0}", OperationContext.Current.SessionId);
return this.result;
}
#endregion
public CSession()
{
Console.WriteLine("CSession is Created!");
}
~CSession()
{
Console.WriteLine("CSession object has been destoried");
}
}
}
客户端调用Co
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace Client
{
class Program
{
static void Main(string[] args)
{
ChannelFactory<Contracts.ISession> factory = new ChannelFactory<Contracts.ISession>("CSession");
try
{
Contracts.ISession s = factory.CreateChannel();
Console.WriteLine("Create s");
Console.WriteLine("Adds(1)");
s.Adds(1);
Console.WriteLine("Adds(2)");
s.Adds(2);
Console.WriteLine("Result:{0}", s.GetResult());
(s as ICommunicationObject).Close();
Contracts.ISession s1 = factory.CreateChannel();
Console.WriteLine("Create s1");
Console.WriteLine("Adds(1)");
s1.Adds(1);
Console.WriteLine("Adds(2)");
s1.Adds(2);
double d1 = s1.GetResult();
Console.WriteLine("Result:{0}", d1.ToString());
(s1 as ICommunicationObject).Close();
}
catch (FaultException<Contracts .MyError> ex)
{
Console.WriteLine(ex.Detail.Message + "--" + ex.Detail.Co
}
Console.Read();
}
}
}