我的情况是这样的。在每次调用我的Web服务时,我都有一个out参数,它是一个错误对象。如果没有错误,则该对象通过空白表示。如果出现错误,那么会填充不同的属性,例如“HasError”字段,“ErrorMessage”,“PrettyMessage”等。我现在想要做的是创建不同类型的Error对象,它们都会实现一个错误我已经定义了接口。然后我希望能够将out参数设置为“out IMyError error”,然后能够将该错误对象设置为该接口的一个实现,具体取决于我在方法中遇到的错误类型。我得到的问题是序列化似乎不喜欢这个。该方法运行良好,但我没有得到任何数据在客户端。这里有一些代码希望澄清。将界面用作WCF Web服务中的输出参数
我的界面
public interface IMyError
{
bool HasError { get; set; }
string ErrorType { get; set; }
string PrettyErrMsg { get; set; }
}
一个例子类实现
[Serializable]
[DataContract]
public class AspError : IMyError
{
public AspError(Exception exception)
{
this.HasError = true;
this.PrettyErrMsg = "An ASP Exception was thrown";
this.ExceptionMsg = exception.Message;
this.StackTrace = exception.StackTrace;
}
[DataMember(Name = "has_error", IsRequired = true)]
public bool HasError { get; set; }
[DataMember(Name = "error_type", IsRequired = true)]
public string ErrorType
{
get
{
return "ASP";
}
set
{
}
}
[DataMember(Name = "pretty_error", IsRequired = true)]
public string PrettyErrMsg { get; set; }
[DataMember(Name = "exception", IsRequired = true)]
public string ExceptionMsg { get; set; }
[DataMember(Name = "stack_trace", IsRequired = true)]
public string StackTrace { get; set; }
}
而在我的WCF服务的方法
public bool MyMethod(out IMyError error)
{
error = new MyError() { HasError = false };
try
{
// do some code
}
catch (Exception exception)
{
error = new AspError(exception);
return false;
}
}
我想是该方法,当一个例外是被捕获,返回一个AspError格式化为json的方式,它在过去的工作方式之前,我尝试了doin将其作为接口。或者,如果发生不同类型的IMyError,则返回THAT类型,格式为json。我认为它可以工作,因为它们都是IMyError类。
谢谢。然而,一个澄清。我其实将属性添加到wcf服务的接口类,而不是像你展示的方法。 – sanpaco 2012-07-27 18:31:07
@sanpaco您是否认为您已将'KnownTypeAttribute'添加到'AspError'或您的'IMyError'接口,因为我认为不可能在接口上添加'KnownType属性',这只能在'struct,枚举或类' – 2016-06-07 15:11:41