CSharp - C# post请求未被标识为会话

  显示原文与译文双语对照的内容
99 4

我一直试图使一个WPF客户机连接到一个PHP服务器,记录本身以验证客户端是否登录。 但是,'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)

为什么服务器没有将请求注册为会话?

时间: 原作者:

111 1

服务器标识客户机( 以及相应的会话状态)的方式是通过 Cookies 。

基本上,在 CreateAccount 请求中,服务器将cookie附加到它的响应,并期望客户机在每个后续请求中呈现 cookie 。

如果cookie不存在于请求中,则服务器无法识别客户端并将请求视为未知来源。

代码根本不管理 Cookies,所以这就是为什么 C# 客户机总是一个新客户端的PHP服务器。

保存从服务器接收的cookie并在每个新请求上呈现它的最简单方法是使用 CookieContainer的实例。

我没有尝试这个代码,所以我没有 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;
}

原作者:
...