我正在尝试从我的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);
}
}
}
答案 0 :(得分:1)
发现问题,这是人为错误。
我的文件dbconnect.php
位于myProblem.php
所在位置下方的一个目录中。
我不得不换行
include_once 'dbconnect.php';
到
include_once '../dbconnect.php';