如何在Soap客户端调用ASP.Net Web服务时保留会话信息

3
这是我的系统设置方式:
  • 使用ASP.Net Web服务的Web服务
  • Web服务具有EnableSession=true的Web方法
  • 客户端使用“Service References”引用Web服务(注意:不是“Web References”)
  • 客户端的app.config具有allowCookies=true
在客户端上,我有以下代码将文件上传到服务。
bool res = service.InitiateUpload();
if (res) {
    do {
        read = stream.Read(buffer, 0, BLOCK_SIZE);
        if (read == BLOCK_SIZE)
            res = res && service.AppendUpload(buffer);
        else if (read > 0)
            // other call to AppendUpload, after buffer manipulation

在服务器端,我有一段代码用于检查从InitiateUpload调用中获取的会话ID是否与AppendUpload相同。

[WebMethod(EnableSession=true)]
public bool InitiateUpload() {
  lock (theLock) {
    if (IsImportGoingOn)
      return false;

    theImportDataState = new ImportDataState(Session.SessionID);
  }
  return true;
}

[WebMethod(EnableSession=true)]
public bool AppendUpload(byte[] data) {
  lock (theLock) {
    if (!IsImportGoingOn)
      return false;

    if (theImportDataState.session != Session.SessionID)
      return false;

    theImportDataState.buffer.AddRange(data);
    return true;
  }
}

调用AppendUpload返回false,因为会话ID不匹配。为什么会这样呢? 据我所见,我已经为Web方法设置了正确的属性,客户端也有正确的配置,并且使用相同的代理实例。我是否漏掉了什么?

2个回答

3

关键是你需要让服务客户端知道它应该关心 cookie -- 默认情况下它不会。

也许更好的方法是,服务传回一个交易 ID,客户端可以在将来使用它来引用上传。从长远来看,这将更加清晰,并且可能比让客户端处理 cookie 和 session 更少工作。


0

你需要使用CookieContainer来保持会话。

private System.Net.CookieContainer CK = new System.Net.CookieContainer();

然后将其用作服务对象的CookieContainer即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接