我是WCF的新手,我正在尝试序列化自定义对象列表。我已经在其他文章中尝试了这些解决方案。
这是服务接口代码:
[ServiceContract]
[ServiceKnownType(typeof(List<Stage>))]
public interface IUserService
{
[OperationContract]
void CreateUser(string name, string pwd, bool admin);
[OperationContract]
bool LogInUser(string name, string pwd);
[OperationContract]
List<Stage> getAllStages();
}
[DataContract]
public class StageListGetter
{
private List<Stage> stageList;
[DataMember]
public List<Stage> StageList
{
get { return stageList; }
set { stageList = value; }
}
}
在服务类中我试过这个:
public List<Stage> getAllStages()
{
StageController sctrl = new StageController();
Dictionary<int, Stage> sdict = sctrl.getAllStages();
List<Stage> StageValueList = sdict.Values.ToList();
StageListGetter sg = new StageListGetter();
sg.StageList = StageValueList;
return sg.StageList;
}
调用时出现以下错误:
This could be due to the service endpoint binding not using the HTTP protocol.
This could also be due to an HTTP request context being aborted by the server (possibly due
to the service shutting down). See server logs for more details.
我错过了什么?
答案 0 :(得分:1)
简单的解决方案是您的Stage类也是[DataContract]
。如果您无法控制Stage
类,则使用公共构造函数创建您自己的[DataContract]
类,获取Stage类的实例并将其内容复制到[DataMember]
元素中。
[ServiceContract]
public interface IUserService
{
[OperationContract]
void CreateUser(string name, string pwd, bool admin);
[OperationContract]
bool LogInUser(string name, string pwd);
[OperationContract]
List<StageContract> getAllStages();
}
public List<StageContract> getAllStages()
{
return (new StageController())
.getAllStages()
.Values
.Select(s => new StageContract(s))
.ToList();
}
答案 1 :(得分:0)
*更新:这是完整的工作实施:
我按以下方式更新了代码:
[ServiceContract]
[ServiceKnownType(typeof(List<StageContract>))]
public interface IUserService
{
[OperationContract]
void CreateUser(string name, string pwd, bool admin);
[OperationContract]
bool LogInUser(string name, string pwd);
[OperationContract]
List<StageContract> getAllStages();
}
我创建了数据合同如下:
[DataContract]
public class StageContract
{
private int _stageID;
private int _projectID;
private int _wip;
private string _name;
private int _position;
public StageContract(Stage s)
{
StageID = s.ID;
ProjectID = s.ProjectID;
WIP = s.WIP;
Name = s.Name;
Position = s.Position;
}
[DataMember]
int StageID
{
get { return _stageID; }
set { _stageID = value; }
}
[DataMember]
int ProjectID
{
get { return _projectID; }
set { _projectID = value; }
}
[DataMember]
int WIP
{
get { return _wip; }
set { _wip = value; }
}
[DataMember]
string Name
{
get { return _name; }
set { _name = value; }
}
int Position
{
get { return _position; }
set { _position = value; }
}
}
服务类有这个方法:
public List<StageContract> getAllStages() {
return (new StageController())
.getAllStages()
.Values
.Select(s => new StageContract())
.ToList();
}