Web Service不会在请求之间保持状态

时间:2011-01-11 18:02:22

标签: php session asmx session-state

我正在开发ASP.NET Web服务:

# MyWS.cs
[WebMethod(EnableSession = true)]
public bool TryLogin(string user, string pass)
{
    if (/* user validation is successful*/)
    {
        Context.Session["user"] = user;
        return true;
    }
    else
    {
        Context.Session.Abandon();
        return false;
    }
}
[WebMethod(EnableSession = true)]
public string RetrieveSomething()
{
    if (Context.Session["user"] == null)
        throw Exception("User hasn't logged in.");
    /* retrieve something */;
}

这个ASP.NET必须由我正在开发的PHP网站使用:

# ws_client.php
function get_soap_client()
{
    if (!isset($_SESSION['client']))
        $_SESSION['client'] = new SoapClient('MyWS.asmx?WSDL');
    return $_SESSION['client'];
}
function try_login($user, $pass)
{
    return get_soap_client()->TryLogin(
        array('user' => $user, 'pass' => $pass))
        ->TryLoginResult;
}
function retrieve_something()
{
    return get_soap_client()->RetrieveSomething(
        array())->RetrieveSomethingResult;
}

# index.html
<?php
    if (isset($_POST['submit']))
    {
        session_start();
        require_once('ws_client.php');
        if (try_login($_POST['user'],
                      $_POST['pass']))
        {
            session_write_close();
            header('Location: /main.php');
            exit();
        }
?>
<html> <!-- login form here >

# main.php
<?php
    session_start();
    require_once('ws_client.php');
    // Here I get the Exception "User hasn't logged in.", even though
    // the user has logged in and the web service has already been notified.
    echo htmlspecialchars(retrieve_something());
?>

我的Web服务或PHP网站可能出现什么问题?

1 个答案:

答案 0 :(得分:1)

我不知道PHP SOAP工具,但会话状态是通过cookie维护的。这段代码是第一次接受cookie,然后在后续的电话中发回吗?