如何在Soap客户端调用ASP.Net Web服务的过程中保留会话

时间:2010-09-14 16:03:16

标签: c# asp.net wcf web-services asmx

以下是我的系统设置方式:

  • 使用ASP.Net网络服务的网络服务
  • Web服务具有EnableSession = true
  • 的Web方法
  • 使用“服务引用”引用Web服务的客户端(注意:不是“Web引用”)
  • 客户端的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;
  }
}

由于会话ID不匹配,对AppendUpload的调用返回false。这是为什么? 据我所知,我有正确的Web方法属性,客户端具有正确的配置,并使用相同的代理实例。我错过了什么吗?

2 个答案:

答案 0 :(得分:3)

诀窍是你需要让服务客户端知道它应该关心cookie - 它默认不是。

或许更好的方法是服务传回客户端可用于在将来引用上传的事务ID。从长远来看,它会更干净,并且可能比使客户端使用cookie以及会话更少工作。

答案 1 :(得分:0)

您必须使用CookieContainer保留会话。

私有System.Net.CookieContainer CK =新的System.Net.CookieContainer();

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