[英]method in WCF service returns nothing
我對方法Final()有一些麻煩。 它應該返回IWeather的列表,但是當我調用它時返回null。 在調試中,我停止了
return this.returner;
但是它始終為null,我不知道為什么,因為在MainMethod()中進行調試時,MainMethod()返回“ finish”,並且列表“ 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;
}
}
您的服務由兩個單獨的操作組成,並在服務類上使用成員變量來嘗試在調用之間存儲狀態。 您也沒有在服務類上指定任何顯式的ServiceBehaviorAttribute
,這意味着默認的InstanceContextMode
將為PerSession
。 但是,我猜您現在實際上並沒有使用會話,因此您基本上會遇到PerCall
行為。
因此,正在發生的是對MainMethod
的調用,該調用獲取AllInOne
服務類的新實例,它執行,填寫returner
字段,但現在該實例已完成並准備好進行GC。 對Final
的下一次調用將獲取AllInOne
類的全新實例,因此永遠不會設置returner
字段,因此該字段為null。
如果要為所有客戶端使用一個實例(也許您只有一個,不知道),則需要使用Single
InstanceContextMode
, 或者需要實際為該服務啟用會話並確保您的客戶端也正確使用了會話。 有關如何使用會話的詳細信息,請參見此處 。
在每次調用WCF服務之間,局部變量都不是持久的,因為每次發出WCF請求時都會創建類的新實例。 您的所有請求都必須彼此獨立,否則您將需要一個持久性存儲容器(例如數據庫)。 或者,您需要使用@DrewMarsh
指示的@DrewMarsh
。
當我調查您的代碼時,我覺得您似乎對WCF有點困惑。 首先,除非您從客戶端調用WCF中的操作合同,否則它本身無法工作。 例如,當您調用final方法時,它僅返回一個列表。 同樣,在主方法中,您返回了一個字符串,即完成。 “完成”不是方法調用,而只是一個字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.