.NET POST到PHP页面

我正在尝试从我的C#.NET应用程序实现一个非常基本的系统,该系统将我的Web服务器上的机器的IP地址发送到authenticate.php。 php页面将针对数据库检查此IP地址,并以“是”或“否”回复。

自从我使用PHP以来已经很长时间了,我有点困惑。 这是我的.NET函数的样子。

public static bool IsAuthenticated() { string sData = getPublicIP(); Uri uri = new Uri("http://www.mysite.com/authenticate.php"); if (uri.Scheme == Uri.UriSchemeHttp) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.Method = WebRequestMethods.Http.Post; request.ContentLength = sData.Length; request.ContentType = "application/x-www-form-urlencoded"; // POST the data to the authentication page StreamWriter writer = new StreamWriter(request.GetRequestStream()); writer.Write(sData); writer.Close(); // Retrieve response from authentication page HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string sResponse = reader.ReadToEnd(); response.Close(); if (sResponse == "yes") { Console.WriteLine("Authentication was Successful."); return true; } else { Console.WriteLine("Authentication Failed!"); return false; } } } 

那么POST变量是$ _POST [‘sData’]; 以及如何用结果回复我的申请?

假设sData的值是(例如)“10.1.1.1”,那么您当前不会首先发布正确的表单数据。 变量的名称不是写入的文本的一部分

  writer.Write(sData); 

你需要做一些事情:

  string postData = "ipaddress=" + sData; 

然后在PHP中使用ipaddress表单参数。

另请注意,您应该提供二进制内容长度,该长度可能与字符串中的字符串长度不同。 当然,如果这里的字符串完全是ASCII,这是可以的,如果它是一个IP地址,我期望它…但是值得注意其他用途。 (同样,您通常需要记住任何需要特殊编码的字符。)

另请注意,最好使用StreamWriterHttpResponse等的using语句来确保即使抛出exception也会关闭所有内容。