Wcf服务如何最好地为同一方法返回不同的对象

时间:2014-02-17 17:19:26

标签: c# wcf

我的Wcf服务有以下界面;

[ServiceContract]
public interface IService
{
    [OperationContract]
    [XmlSerializerFormat]
    [WebInvoke(Method = "POST", UriTemplate = "/GetTypes", BodyStyle = WebMessageBodyStyle.Bare)]
    object GetTypes(RequestObject RequestObject);

}

我的服务看起来像这样;

public class Service : IService
{
   public static GetTypes(RequestObject RequestObject)
   {
        if(RequestObject.Validate)
        {
            //create a new response obj, and return it
            ResponseObj oResponseObj = new ResponseObj();
            //get some data from data source and populate object, then return it
            return oResponseObj;
        }
        else
        {
            //error response
            ErrorResponseObj oErrorResponseObj = new ErrorResponseObj();
            oErrorResponseObj.ErrorId = 1;
            oErrorResponseObj.ErrorMessage = "There was a error";
            return oErrorResponseObj;
        }
   }
}

我的回复对象是

[DataContract]
public class ResponseObj
{
    [DataMember]        
    public int Id {get;set;}

    [DataMember] 
    public List<string> Names {get;set;}
}

我也有像

这样的错误回复
[DataContract]
public class ErrorResponseObj
{
    [DataMember]        
    public int ErrorId {get;set;}
    [DataMember]
    public string ErrorMessage {get;set;}
    [DataMember]
    public string MessageImportance {get;set;}
}

我应该如何最好地将这些不同的对象返回到Wcf方法。我应该返回类型对象吗?或者有更好的选择,或者这是正确的方法。

2 个答案:

答案 0 :(得分:1)

执行此类操作的标准方法是使用FaultContractAttribute。 Fault contract允许您指定将在SOAP Fault内返回的备用响应。 Philippe Truche给出了一个很好的例子,说明了这些在电线on his blog上看起来如何。

示例界面:

[ServiceContract]
interface IService
{
    [OperationContract]
    [FaultContract(typeof(ErrorResponseObj))]
    ResponseObj GetObj();
}

服务:

class Service : IService
{
    public ResponseObj GetObj()
    {
        if (success)
        {
            return new ResponseObj();
        }
        else
        {
            throw new FaultException<ErrorResponseObj>(new ErrorResponseObj() 
            {
                ErrorMessage = "Something Happened"
            })
        }
    }
} 

然后,客户端可以通过捕获FaultException<ErrorResponseObj>

来处理错误
var serviceProxy = new ServiceProxy();

try 
{
    var dataObj = serviceProxy.GetObj();
}
catch (FaultException<ErrorResponseObj> error)
{
    ErrorResponseObj detail = error.Detail;
    Console.WriteLine(detail.ErrorMessage);
}

答案 1 :(得分:0)

您可以将其聚合为一种类型:

[DataContract]
public class ResponseObj
{
   [DataMember]        
   public int ErrorId {get;set;}
   [DataMember]
   public string ErrorMessage {get;set;}
   [DataMember]
   public string MessageImportance {get;set;}
   [DataMember]
   public int Id {get;set;}
   [DataMember]
   public List<string> Name {get;set;}
}

然后你会检查ErrorId是否是&gt; 0,否则没有错误。

另一种方法是在WCF服务中抛出一个Fault Exception,以便处理它 客户方:

http://blogs.msdn.com/b/endpoint/archive/2011/01/14/wcf-spike-faultcontract-faultexception-lt-tdetail-gt-and-validation.aspx