在WCF Web服务中使用接口作为out参数

时间:2012-07-27 02:58:41

标签: c# json wcf serialization interface

我的情况是这样的。在每次调用我的Web服务时,我都有一个out参数,它是一个错误对象。如果没有错误,则对象通过为空指示。如果有错误,则填充不同的属性,例如“HasError”字段,“ErrorMessage”,“PrettyMessage”等。我现在要做的是创建不同类型的Error对象,它们都实现了一个错误我已经定义过的界面。然后我希望能够将out参数设置为“out IMyError error”,然后能够将该错误对象设置为我的某个接口实现,具体取决于我在方法中遇到的错误类型。我得到的问题是序列化似乎不喜欢这样。该方法运行正常,但我没有在客户端获得任何数据。以下是一些希望澄清的代码。

我的界面

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;
    }
}

我想要的是该方法,当捕获到异常时,在我尝试将其作为接口之前返回格式为json的AspError,就像它过去一样。或者,如果发生了不同的已实现的IMyError类,则返回格式为json的THAT类型。我认为它可以工作,因为它们都是IMyError类。

1 个答案:

答案 0 :(得分:3)

您需要向客户端发送提示如何反序列化您的界面。 WCF使用KnownTypeAttribute执行此操作。

您的服务应更改为:

[KnownType(typeof(AspError))]
public bool MyMethod(out IMyError error)
{
    ...
}

您可以在MSDN中找到更多详细信息 - http://msdn.microsoft.com/en-us/library/ms730167.aspx

当然,您的客户端应该可以访问类型AspError的程序集,以便能够构造该类型。