Return 来自 WCF 服务的不同对象(列表或错误 class)

Return different Object (List or error class) from WCF service

我正在尝试构建一个 WCF 服务,它只有一个方法 getPersonList return 像这样的人列表

[
  {"personId":121, "personName":"John Smith"},
  {"personId":953, "personName":"Maggie Johnson"}
]

如果出现错误,我想 return 从相同的方法得到这样的错误响应。

{"errorCode":4002,"errorMessage":"invalid request token"}

现在我的服务合同如下:

    [ServiceContract()]
    public interface IPersonContract
    {
        [OperationContract()]
        Object GetPersonList(int requestParam);
    }

和我的示例 GetPersonList 方法

Object GetPersonList(int requestParam)
{
  if (requestParam == 1)
  {
    ErrorResponse error = new ErrorResponse();
    error.ErrorCode = 4002;
    error.ErrorMessage = "invalid request token";

    return error;
  }else
  {
    List<Person> returnList = new List<Person>();
    // add Person to returnList
    return returnList;
  }

}

人Class

[DataContract()]
public class Person
{

    [DataMember(Name = "personName")]
    String PersonName{   get;   set;  }

    [DataMember(Name = "personId")]
    String PersonID {   get;   set;  }

}

错误Class

[DataContract()]
public class ErrorResponse
{

    [DataMember(Name = "errorCode")]
    int ErrorCode{   get;   set;  }

    [DataMember(Name = "errorMessage")]
    String ErrorMessage{   get;   set;  }

}

我在 KnownTypes 中查找了 DataContract classes,但如何将其应用到 Object

如果我从 ErrorReponse 添加字段并在单个 class 和 return 该对象中添加 List<Person> ,我在成功案例中得到这样的响应不是我想要的。

{
"Person":[{"personId":121, "personName":"John Smith"},
      {"personId":953, "personName":"Maggie Johnson"}]
}

更改您的服务合同定义,如 -

    [OperationContract]
    [WebInvoke(Method = "GET",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    UriTemplate = "/get/{id}")]
    [ServiceKnownType(typeof(RootObject1))]
    [ServiceKnownType(typeof(RootObject2))]
    object GetOrder(string id);

服务实施-

    public object GetOrder(string id)
    {
        if (id.Length == 1)
        {
            return new RootObject1 { errorCode = 4002, errorMessage = "invalid request token" };
        }
        return new RootObject2 { personId = 121, personName = "John Smith" };
    }


2016 年 12 月 27 日更新列表类型

    [OperationContract]
    [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, Method = "GET", UriTemplate = "GetOrdersJSON?ClientID={ClientID}&SenderEmail={SenderEmail}&VersionNumber={VersionNumber}")]
    [ServiceKnownType(typeof(List<MyCustomErrorDetail>))]
    [ServiceKnownType(typeof(List<ShipToDetails>))]
    object GetOrdersJSON(int ClientID, string SenderEmail, string VersionNumber);


[DataContract]
public class MyCustomErrorDetail
{
    public MyCustomErrorDetail(string errorInfo, string errorDetails)
    {
        ErrorInfo = errorInfo;
        ErrorDetails = errorDetails;
    }

    [DataMember]
    public string ErrorInfo { get; private set; }

    [DataMember]
    public string ErrorDetails { get; private set; }
}

Return 当没有记录或根据您的需要发生任何其他错误时,来自 GetOrdersJSON 的以下对象!

                MyCustomErrorDetail myCustomErrorObject = new MyCustomErrorDetail("There are no records available", string.Format("There are no records available for user {0}", fstr_UserName));
                List<MyCustomErrorDetail> myCustomErrorList = new List<MyCustomErrorDetail>();
                myCustomErrorList.Add(myCustomErrorObject);
                return myCustomErrorList;

在我的中,我刚刚返回了一个标准的 HTTPResponseException,如下所示:

    public clsUserInfo Get(String id, String pwd)
    {
        clsResultsObj<clsUserInfo> retVal = new clsResultsObj<clsUserInfo>();

        retVal = bizClass.GetUserByIDAndPWD(id, pwd);

        if (retVal.IsSuccessful & retVal.Payload != null)
        {
            return retVal.Payload;
        }
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }

    }

但是您可以更进一步,为您自己的自定义错误消息添加类似这样的内容:

{ 
    throw new WebFaultException<string>(string.Format(“There is no user with the userName ‘{0}’.”, userName), HttpStatusCode.NotFound); 
}