我遇到了方法Final()的麻烦。它应该返回IWeather的列表,但是当我调用它时返回null。在调试中我停在了
return this.returner;
但它总是为null而且我不知道为什么因为MainMethod()返回“finish”并且当调试在MainMethod()中时列表“returner”不为null。
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using LibW;
[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class AllInOne
{
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}
[DataMember]
private List<LibW.IWeather> returner = new List<LibW.IWeather>();
/// <summary>
/// method set connection to google and get xml document weather for there
/// </summary>
/// <param name="city">city for which find weather</param>
/// <param name="lang">lang of text</param>
/// <returns>return either "finish if all successful or Exception msg or errors with city finding and error with connection</returns>
[OperationContract]
public string MainMethod(string city, string lang)
{
//check connection
Ping p = new Ping();
PingReply pr = p.Send(@"google.com");
IPStatus status = pr.Status;
if (status != IPStatus.Success)
return "Error with Connection";
//try tp get xml weather
try
{
XElement el;
HttpWebRequest req =
(HttpWebRequest) WebRequest.Create("http://www.google.com/ig/api?weather=" + city + "&hl=" + lang);
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
StringBuilder sb = new StringBuilder();
using (StreamReader streamreader = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(1251)))
{
el = XElement.Load(streamreader);
}
int addv = 0;
var v = from c in el.Elements()
select c;
//I get here data from XML(condition,temperature and etc.)
return "finish";
}
catch (Exception exc)
{
return exc.Message;
}
}
/// <summary>
/// return list of weather fot 4 days
/// </summary>
/// <returns>list</returns>
[OperationContract]
public List<IWeather> Final()
{
return this.returner;
}
}
答案 0 :(得分:3)
您的服务由两个单独的操作组成,并使用服务类上的成员变量来尝试在调用之间存储状态。您也不在服务类上指定任何明确的ServiceBehaviorAttribute
,这意味着默认InstanceContextMode
将是PerSession
。但是,我猜你现在实际上并没有使用会话,因此你基本上会以PerCall
行为结束。
所以,正在发生的是MainMethod
的调用,它获取AllInOne
服务类的新实例,它执行,填写returner
字段,但现在实例已完成并准备好进行GC。对Final
的下一次调用会获得AllInOne
类的全新实例,因此returner
字段永远不会被设置,因此为空。
如果您想为所有客户提供一个实例(可能只有一个,不知道)或,您需要使用InstanceContextMode
Single
实际启用服务的会话,并确保您的客户端也正确使用会话。有关如何使用会话的详细信息,请here。
答案 1 :(得分:1)
在调用WCF服务之间,局部变量不是持久的,因为每次发出WCF请求时都会创建一个新的类实例。您的所有请求都需要彼此独立,否则您需要一个持久存储容器,例如数据库。或者您需要使用会话,如@DrewMarsh
所示。
答案 2 :(得分:1)
当我调查你的代码时,我觉得你对WCF有点困惑。首先,除非您从客户端调用WCF中的操作合同,否则它本身不起作用。例如,当您调用方法final时,它只返回一个列表。 此外,在mainmethod中,您返回了一个字符串,即完成。 “完成”不是方法调用,只是一个字符串。