我已上传具有以下契约(Contract)的服务。
[ServiceContract]
public interface Service
{
[OperationContract]
void CreateThing(Thing thing);
[OperationContract]
List<Thing> RetrieveThings();
}
当我调用创建方法时,一切正常,实例已在数据库中创建,并且没有任何错误。但是,当我检索元素时,出现错误:
The remote server returned an unexpected response: (502) Bad Gateway.
奇怪的是,当列表为空(数据库中没有元素)时,操作会顺利进行。更奇怪的是,针对数据库的操作在服务器内部工作,如果我聚合元素的名称并将它们作为字符串发送出去或打包在类 Thing 的字符串属性中,它也有效!
这就是它不起作用时的样子:
public List<Thing> RetrieveThings()
{
List<Thing> output;
using (Context context = new Context())
output = context.Things.ToList();
return output;
}
这就是它工作时的样子:
public List<Thing> RetrieveThings()
{
List<Thing> output = new List<Thing>();
using (Context context = new Context())
foreach (Thing thing in context.Things.ToList())
output.Add(new Thing {Id = thing.Id, Name = thing.Name});
return output;
}
我在这里做了什么不同的事情(在幕后而不是有意识地)?显然我可以访问数据库并且我有特权。我也可以读出所有信息。尽管如此,由于某种原因我必须创建对象的副本。我需要逐一执行此操作,而不是使用 LINQ 查询。很困惑...
最佳答案
我认为这可能与序列化有关。
context.Things.ToList()
此代码看起来像是您正在从服务发回 EntityObject。尝试使用 POCO 而不是使用“Thing”接口(interface)怎么样?或者,您可以转换/转换对象并返回它?
context.Things.ToList()ToAnotherPlainClass()
您的“Thing”类只有两个属性吗?你能像这样返回而不循环吗?
public List<Thing> RetrieveThings()
{
List<Thing> output;
using (Context context = new Context())
output = (from t in context.Things
select new Thing() {
Id = t.Id, Name = t.Name
}
).ToList();
return output;
}
你查过this one on MSDN吗? ?我还没有测试过,但似乎您需要应用[ApplyDataContractResolverAttribute]
。
在我的大多数项目中,我曾经创建与实际实体不同的响应模型,因此我没有遇到您现在遇到的问题。如果您还没有尝试过ApplyDataContractResolverAttribute,我建议您应该尝试一下。
关于c# - 远程服务器返回意外响应 : (502) Bad Gateway in Azure WCF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35446115/