【问题标题】:How to retain sessions across calls to an ASP.Net web service from a Soap client如何在从 Soap 客户端调用 ASP.Net Web 服务时保留会话
【发布时间】:2010-09-14 16:03:15
【问题描述】:

这是我的系统的设置方式:

  • 使用 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 方法属性,客户端有正确的配置,并且使用了相同的代理实例。我错过了什么吗?

【问题讨论】:

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


    【解决方案1】:

    诀窍是您需要让服务客户端知道它应该关心 cookie——默认情况下它不关心。

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

    【讨论】:

      【解决方案2】:

      您必须使用 CookieContainer 来保留会话。

      私有 System.Net.CookieContainer CK = new System.Net.CookieContainer();

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 2012-05-31
        相关资源
        最近更新 更多