从C#Windows窗体调用PHP Web服务

I am trying to verify username, password, and software token number of a C# Windows Form to values in MySQL database.

My C# Code:

 private void btnlogin_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(txtusername.Text))
        {
            MessageBox.Show("Please insert username");
        }

        if (String.IsNullOrEmpty(txtpassword.Text))
        {
            MessageBox.Show("Please insert password");
        }

        var username = txtusername.Text;
        var password = txtpassword.Text;
        string Token = "28956";
        var SoftwareToken = token;
        WebRequest request = WebRequest.Create("https://mydomain.com.au/Verification.php?username=username&password=password&Token=SoftwareToken");
        request.Method = "GET";
        WebResponse response = request.GetResponse();
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        Stream dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.  
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.  
        var responseFromServer = reader.ReadToEnd();
        responseFromServer.ToArray();
        /*I have tried:
        responseFromServer.ToArray();(because result on php page is an array.
  I have tried responseFromServer.ToString();*/
        MessageBox.Show(responseFromServer);
    }

My PHP code (Web service):

<?php
// Database Structure 
require_once('connect.php');

//Get password from the database for the user
$stmtus = $conn->prepare("SELECT password from `Users` where `email` = :Username");
$stmtus->bindParam(':Username', $username);
$username= $_GET['username'];;
$stmtus -> execute();
$password = $stmtus->fetch();

$un = $_GET['username'];
$pw = $_GET['password'];
$ust = $_GET['Token'];

if(password_verify($pw, $password[0])){
    $stmt = $conn->prepare("SELECT 
    COUNT(Token) AS cnt FROM `SoftwareToken` 
    LEFT JOIN User ON iduser = SoftwareToken.Consultant 
    WHERE Token = '$ust' 
    AND username = '$un'");
    $stmt->bindValue(':Username', $un);
    $stmt->bindValue(':Token', $ust);
    $stmt->execute();
    $result= array();
    while($SToken= $stmt->fetch(PDO::FETCH_OBJ)){
    array_push($result, $SToken->cnt);  
    }
echo json_encode($result);

}

$conn = null;

?>

I am battling to understand how I call the web service from the C# application, how do I pass the variables from the C# application to the web service and how do I return the json_encode to the C# application from the web service.

I am not a full-time programmer and this is my first encounter with web services. If there are any suggestions on how to improve either of the codes, I would much appreciate.

UPDATE

I have updated my code as assisted. When I run the php code with variables it runs and gives me a $result (array). A numeral answer 1.

When I test my code to display the result in a MessageBox, the MessageBox is empty. Why ?

dongyi1748
dongyi1748 谢谢你的建议。我认为我将变量从C#Windows窗体应用程序传递给PHPWeb服务失败。请在这里查看我的新问题。也许你有一些建议?
一年多之前 回复
drkxgs9358
drkxgs9358 “如果对如何改进任何代码有任何建议,”好吧,看起来你已经使用正确的php库来处理密码,我想编写并使用预处理语句来防止SQL注入..然后我注意到了这个WHEREToken='$ust'ANDusername='$un'“);在仍然容易进行SQL注入的SQL代码中,你应该用WHEREToken=:TokenANDusername=:Username)进行参数化;
一年多之前 回复
douliangpo0128
douliangpo0128 这或多或少是一个重复的问题..如果你在PHP代码中将$_GET更改为$_POST,你可以使用该答案。
一年多之前 回复

2个回答



当然你可以从C#调用WebService。
系统中有一个内置的calss。</ p>

< p>单向:</ p>

  WebRequest request = WebRequest.Create(“http:// localhost:8080 /?username = john”); 
request.Method =“GET” ;

WebResponse response = request.GetResponse();
</ code> </ pre>

其他方式:</ p>

  HttpClient client = new HttpClient  (); 
client.BaseAddress = new Uri(“http:// localhost:8080 /”);
HttpResponseMessage response = await client.PostAsJsonAsync(“api / user”,userName);
response.EnsureSuccessStatusCode();
</ code> </ pre>
</ div>

展开原文

原文

Of course you can call WebService from C#. There is a built in calss in System.

One Way:

WebRequest request = WebRequest.Create("http://localhost:8080/?username=john");
request.Method="GET";
WebResponse response = request.GetResponse();

Other Way:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8080/");
HttpResponseMessage response = await client.PostAsJsonAsync( "api/user", userName);
response.EnsureSuccessStatusCode();

doude4924
doude4924 谢谢你的建议。 我认为我将变量从C#Windows窗体应用程序传递给PHP Web服务失败。 请在这里查看我的新问题。 也许你有一些建议?
一年多之前 回复
douhe3313
douhe3313 以下是您获得结果的示例:docs.microsoft.com/en-us/dotnet/framework/network-programming / ... 顺便说一句,在我看来,HttpClinet更好
一年多之前 回复
douwen5690
douwen5690 if((int)response = 1){#dosomething}不起作用。 相同的错误:无法将int类型隐式转换为System.Net.WebResponse
一年多之前 回复
dpqaaczn141761
dpqaaczn141761 请将铸造if((int)response = 1){#dosomething}
一年多之前 回复
donglong2856
donglong2856 我做到了。 如何在我的c#中使用响应? 当我这样做(response = 1){#dosomething}我得到错误“无法将类型int转换为webresponse”
一年多之前 回复
doufen5175
doufen5175 请将问题提交答案。 谢谢:)
一年多之前 回复
dongxi5505
dongxi5505 非常感谢。 我喜欢第一种方法。 要在C#应用程序中使用结果,我是否使用if(response = 1){#dosomething}?
一年多之前 回复

Code which I used:

    var username = txtusername.Text;
    var password = txtpassword.Text;
    string Token = "28956";
        var url = "https://mydomain.com.au/LoginVerification.php?";
        var var = "username=" + username + "&password=" + password + "&Token=" + Token ;
        var URL = url + var;
        //MessageBox.Show(URL);


        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.  
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.  
        var responseFromServer = reader.ReadToEnd();
        //MessageBox.Show(responseFromServer);
        // Display the content.  
        if (responseFromServer == "
  Allow")
        {
            MessageBox.Show("Success");           
        }
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐