从WCF服务返回不同的Object(List或错误类)

时间:2016-04-21 13:33:59

标签: c# wcf datacontract

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

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

如果有错误,我想从同一方法返回这样的错误响应。

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

}

人类

[DataContract()]
public class Person
{

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

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

}

错误类

[DataContract()]
public class ErrorResponse
{

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

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

}

我查找了KnownTypes的DataContract类,但是如何在Object上应用它。

如果我从ErrorReponse添加字段并在单个类中添加List<Person>并返回该对象,我会在成功的情况下得到这样的响应,这不是我想要的。

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

2 个答案:

答案 0 :(得分:3)

更改服务合约定义,例如 -

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

enter image description here

enter image description here

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

当没有记录或根据您的需要发生任何其他错误时,从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;

答案 1 :(得分:0)

在我的工作中,我刚刚返回了一个标准的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); 
}
豫ICP备18024241号-1