[英]How to pass the Object complex (DTO) into WCF Post method using C#
[英]How to return DTO object from WCF C#?
我有一个wcf服务,我想返回一个dto对象,然后我想使用WSDL参考服务从其他应用程序Web ASP.net使用服务,但不能在dto客户端应用程序中从wcf进行dto。
并显示此错误:
无法将类型'ClientApp.ClientWs.Client'隐式转换为'CoreApp.DTO.Client
dto“客户端”在两个应用程序中都相同
DTO
public class Client
{
public string status { get; set; }
public string message { get; set; }
public List<Sales> listSales { get; set; }
public Client()
{
listSales = new List<Sales>();
}
}
WCF服务:
public Client getClientByID(string id)
{
List<Sales> list = null;
Client clientResponse = null;
try
{
list = new List<Sales>();
list = bll.getInstance.listSales(id);
clientResponse = new Client();
clientResponse.status = "ok";
clientResponse.message = "success";
foreach (var item in list)
{
clientResponse.listSales.Add(item);
}
}
catch (Exception ex)
{
clientResponse = new Client();
clientResponse.status = "error";
clientResponse.message = ex.Message;
}
return clientResponse;
}
方法应用客户端:
public static List<Sales> getByIdWebService(string id)
{
List<Sales> list = null;
ClientWs.ClientWsClient ws = new ClientWs.ClientWsClient;
Client response = new Client();
response = ws.getClientByID(id); //show error
if (response.status == "error")
{
throw new Exception(response.message);
}
else
{
list = new List<Sales>();
list = response.listSales();
}
}
您可以通过更改代理类来解决此问题。
您是否必须将WCF服务作为WSDL Web参考添加到Web应用程序?
如果将其添加为真实的服务引用,则可以选择重新使用其他程序集(包括DTO)的选项。
编辑:可能有一种方法可以对WSDL引用执行相同的操作,但是它可能并不那么简单...至少,这是我不了解它的借口:)
首先,您可能希望使用[DataContract]
和[DataMember]
装饰器将DTO类和成员标记为可序列化:
namespace DtoClassLib
{
[DataContract]
public class Sales
{
[DataMember]
public string Name { get; set; }
}
[DataContract]
public class Client
{
[DataMember]
public string status { get; set; }
[DataMember]
public string message { get; set; }
[DataMember]
public List<Sales> listSales { get; set; }
public Client()
{
listSales = new List<Sales>();
}
}
}
将引用添加到WCF服务时,选择“添加服务引用”选项,“高级设置”,选择“在引用的程序集中重用类型”复选框,并专门添加WCF服务和Web应用程序使用的DTO程序集:
请小心using
/最终尝试块正确包装服务代理:
public static List<Sales> getByIdWebService( string id )
{
List<Sales> list = null;
using ( WcfSvcRefAsWsdl.ClientWsClient wsdlClient = new WcfSvcRefAsWsdl.ClientWsClient() )
{
// The following will not compile
// DtoClassLib.Client returnClient = wsdlClient.getClientByID( id );
}
using ( WcfSvcRef.ClientWsClient wcfClient = new WcfSvcRef.ClientWsClient() )
{
// Joy! \o/
DtoClassLib.Client client = wcfClient.getClientByID( id );
list = client.listSales;
}
return list;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.