C# 从WCF服务返回不同的对象(列表或错误类)
我正在尝试构建一个WCF服务,它有一个方法C# 从WCF服务返回不同的对象(列表或错误类),c#,wcf,datacontract,C#,Wcf,Datacontract,我正在尝试构建一个WCF服务,它有一个方法getPersonList,该方法返回如下人员列表 [ {"personId":121, "personName":"John Smith"}, {"personId":953, "personName":"Maggie Johnson"} ] 如果有错误,我想从同一个方法返回这样的错误响应 {"errorCode":4002,"errorMessage":"invalid request token"} 现在我的服务合同如下: [S
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 ErrorResponse
{
[DataMember(Name = "errorCode")]
int ErrorCode{ get; set; }
[DataMember(Name = "errorMessage")]
String ErrorMessage{ get; set; }
}
我查找了DataContract类的KnownTypes
,但如何将其应用于对象
如果我从errorresponse
中添加字段,并在单个类中添加List
,然后返回该对象,那么在成功案例中我会得到这样的响应,这不是我想要的
{
"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日更新
[运营合同]
[WebInvoke(BodyStyle=WebMessageBodyStyle.Bare,ResponseFormat=WebMessageFormat.Json,Method=“GET”,UriTemplate=“GetOrdersJSON?ClientID={ClientID}&SenderEmail={SenderEmail}&VersionNumber={VersionNumber}”)]
[ServiceKnownType(类型(列表))]
[ServiceKnownType(类型(列表))]
对象GetOrdersJSON(int ClientID、字符串SenderEmail、字符串VersionNumber);
[数据合同]
公共类MyCustomErrorDetail
{
公共MyCustomErrorDetail(字符串errorInfo、字符串errorDetails)
{
ErrorInfo=ErrorInfo;
ErrorDetails=ErrorDetails;
}
[数据成员]
公共字符串ErrorInfo{get;private set;}
[数据成员]
公共字符串错误详细信息{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;
MyCustomErrorDetail myCustomErrorObject=new MyCustomErrorDetail(“没有可用的记录”,string.Format(“没有可供用户{0}使用的记录”,fstr_用户名));
List myCustomErrorList=新列表();
添加(myCustomErrorObject);
返回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));
}
}
public-clsUserInfo-Get(字符串id,字符串pwd)
{
clsResultsObj retVal=新的clsResultsObj();
retVal=bizClass.getUserById和pwd(id,pwd);
if(retVal.issusccessful&retVal.Payload!=null)
{
返回返回有效载荷;
}
其他的
{
抛出新的HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
}
但是,对于您自己的自定义错误消息,您可以进一步使用类似于以下内容的内容:
{
throw new WebFaultException<string>(string.Format(“There is no user with the userName ‘{0}’.”, userName), HttpStatusCode.NotFound);
}
{
抛出新的WebFaultException(string.Format(“没有用户名为“{0}.”的用户),HttpStatusCode.NotFound);
}
检查此链接,yuo错过了[WebMethod…]装饰,我认为将响应序列化为JSON并让客户端确定(反序列化后)是否发生错误不是更容易吗?@cfrozendath-这只是一个复杂场景的简单示例。可能存在多个错误条件。所以我们需要不同的正负结构cases@KarouiHaythem-谢谢,我忘了在这个例子中补充一点,简单地利用WCF已经提供的机制:使用FaultContracts并抛出FaultException。搜索“wcf故障处理”以查找大量信息。谢谢,我不知道关于ServiceKnownType
。一定要看一看
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);
}