我一直在尝试让WPF客户端连接到PHP服务器,登录并获取“IsLogged.php”#39;验证客户端是否已登录。但是,' IsLogged.php'总是返回客户端未经过身份验证,我做错了什么?
Servercode:
" CreateAccount.php"
session_start();
if (isset($_POST['user']))
{
$_SESSION['UserName'] = $_POST['user'];
echo "check";
}
" IsLogged.php"
session_start();
if (isset($_SESSION['UserName']))
{
echo "allowed";
}
else
{
echo "not allowed";
}
客户代码:
"邮政"方法
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = Request.GetResponse();
dataStream = response.GetResponseStream();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}
最后窗口触发POST请求。
HttpStatusCode Code;
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (intended)
MessageBox.Show(General.Post("CreateAccount", "user=jan", out Code)); --> check (intended)
MessageBox.Show(General.Post("IsLogged", "", out Code)); --> Not allowed (should be allowed)
为什么服务器没有将请求注册为会话?
答案 0 :(得分:0)
服务器识别客户端(以及相应的会话状态)的方式是通过cookie。
基本上,在CreateAccount
请求中,服务器将cookie附加到其响应中,并期望客户端在每个后续请求中显示cookie。
如果请求中不存在cookie,则服务器无法识别客户端并将请求视为来自未知来源。
您的代码根本不管理cookie,因此这就是C#客户端似乎总是成为PHP服务器的新客户端的原因。
保存从服务器收到的Cookie并在每个新请求中显示的最简单方法是使用CookieContainer
和attach it to every request you make的实例。
我没有尝试这段代码,所以我不是100%确定语法,但这是一个起点:
// this instance will be reused across multiple requests
private static CookieContainer cookieContainer = new CookieContainer();
public static string Post(string RequestName, string PostData, out HttpStatusCode ReturnCode)
{
byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
WebRequest Request = WebRequest.Create(ChatAPI.Settings.BaseUrl + RequestName);
Request.Method = "POST";
Request.ContentType = "application/x-www-form-urlencoded";
Request.ContentLength = byteArray.Length;
Request.CookieContainer = cookieContainer; // this line is new
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = Request.GetResponse();
dataStream = response.GetResponseStream();
ReturnCode = ((HttpWebResponse)response).StatusCode;
StreamReader reader = new StreamReader(dataStream);
string returnedData = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return returnedData;
}