从浏览器调用时为什么MySQL结果正常,但从C#调用时为空或NULL?

时间:2017-04-08 17:37:46

标签: c# php mysql null

我正在尝试从我的C#Windows应用程序到我的网站进行webrequest, 但是,当仅从C#调用时,所需结果为空或为null,而不是从预期工作的网站调用。

在我提出请求之前,我需要以login request开头,它按预期工作,并确实返回正确的值。

重要编辑:

我尝试将PHP代码复制到我的login.php文件中,它在C#中工作并返回正确的计数值。

我的HttpClient配置不正确吗?

我的PHP测试代码如下所示:

<?php
    session_start();
    if(!isset($_SESSION['user'])){ header("Location: index.php"); }

    include_once 'dbconnect.php'; //contains $db

    $sql = "SELECT * FROM myTable"; //contains two rows
    $sql_res = mysqli_query($db, $sql);
    $proxyCount = mysqli_num_rows($sql_res);
    $echo "Count: ".$proxyCount;
?>

我的C#看起来像这样:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using System.Net.Http;

using ModernHttpClient;
using Newtonsoft.Json;


namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void log(string str)
        {
            logbox.AppendText(str + Environment.NewLine);
        }

        private string host = "http://www.mywebsite.com/";
        private HttpClient httpClient = new HttpClient(new NativeMessageHandler());
        private async Task<string> request(string target, Dictionary<string, string> _parameters)
        {
            string uri = host + target;

            using (HttpResponseMessage response = await httpClient.PostAsync(uri, new FormUrlEncodedContent(_parameters)))
                return new StreamReader(await response.Content.ReadAsStreamAsync()).ReadToEnd();

        }

        private async void button1_Click(object sender, EventArgs e)
        {

            string loginResp = await request("login.php", new Dictionary<string, string> { { "username", "user" }, { "password", "password" } });
            log(loginResp); 



        }

        private async void button2_Click(object sender, EventArgs e)
        {
            string proxiesResp = await request("proxy/proxy.php", new Dictionary<string, string> { { "getAllProxyRequests", "" } });
            //above returns "count: " in C#, but returns  "count: 2" in webbrowser
            log(proxiesResp);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

发现问题,这是人为错误。

我的文件dbconnect.php位于myProblem.php所在位置下方的一个目录中。

我不得不换行

include_once 'dbconnect.php';

include_once '../dbconnect.php';