我有一个 WCF 休息服务,我试图从同一个网站上的 aspx 页面调用它(即休息和网站都在同一个网站上)。我需要保持会话活跃。发生以下情况
如果我不传递会话 cookie,服务会创建一个不同的会话。如果我通过 Session cookie,httpwebrequest 需要很长时间,然后超时。
有什么我做错了吗?或者也许有更好的方法来调用 REST 服务,同时保持调用 asp.net 页面的相同会话。
我有以下休息签名:
[OperationContract()]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string GetFilterQuery(LookupRequestDTO request);
从代码隐藏我调用这个服务如下:
HttpWebRequest req = WebRequest.Create(url)
as HttpWebRequest;
req.Method = "POST";
req.Credentials = CredentialCache.DefaultNetworkCredentials;
string result = null;
req.ContentType = "application/json";
req.Referer = this.Page.Request.Url.AbsoluteUri;
var cookieContainer = new CookieContainer();//pass session state;
cookieContainer.Add(new Cookie() { Domain = req.RequestUri.Host, Name = "ASP.NET_SessionId", Value = HttpContext.Current.Session.SessionID });
req.CookieContainer = cookieContainer;
string data = null;
//code that populates data goes here ... (excluded for simplification)
using (Stream webStream = req.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(data);
}
using (HttpWebResponse resp = req.GetResponse() //timeout occurs here
as HttpWebResponse)
{
StreamReader reader =
new StreamReader(resp.GetResponseStream());
}
使用 $.ajax 方法从 javascript 调用时,该服务正常工作并保持相同的会话