【问题标题】:Retrieve/fetch data to display to my ASP.Net web application from PHP service thats connected to remote MySQL database从连接到远程 MySQL 数据库的 PHP 服务检索/获取数据以显示到我的 ASP.Net Web 应用程序
【发布时间】:2018-02-11 17:33:01
【问题描述】:

所以我有一个远程(托管)MySQL 数据库,我通过 PHP 服务连接到该数据库。我需要我的 ASP.Net c# web 应用程序和我的 android 来与之通信。但是,我正在努力使用从服务中检索到的所有信息填充我的 Web 应用程序模板。例如,我想填充用户的个人资料页面。

下面是我与数据库的 PHP 连接和通信:

    `// Create connection
         $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM Vendor Where VendorId = 2"; //this is just a test
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo . $row["id"]. . $row["BusinessName"]. . $row["Location"]. . $row["Email"]. .$row["Website"]. .$row["ProductType"]. .$row["Contact"]. .$row["PaymentOption"]. .$row["ProfileImg"]."<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
` 

然后(不分享我的所有设置)这将是 asp.net c# 与我的 PHP 文件/服务通信的代码示例。

public void getUserInfo(int id)
        {


            string BusinessName = lblBusiness.Text.Trim();
            string email = lblEmail.Text.Trim();
            string Contact = lblPhone.Text.Trim();

            string location = lblLocation.Text.Trim();
            string Website = lblWebsite.Text.Trim();

            string payment = lblPayment.Text.Trim();

            //Variables to get information from the service
            Stream dataStream = null;
            WebResponse response = null;
            StreamReader reader = null;
            //Stores the result from the server
            string responseFromServer = null;
            try
            {
                string requestMethod = "GET";
                //Sending this data across the stream
                string postData = "&Email=" + email +   "&BusinessName=" + BusinessName + "&Website=" + Website + "&PaymentOption=" + payment + "&Location=" + location + "&ProductType=" + ProductType + "&Contact=" + Contact + "";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                string URL = "";// url of php service location
                string contenttype = "application/x-www-form-urlencoded";
                //Create link to web service
                WebRequest request = WebRequest.Create(URL);
                //Pass the request method
                request.Method = requestMethod;
                request.ContentType = contenttype;
                request.ContentLength = byteArray.Length;
                dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                //Get response from the server
                response = request.GetResponse();
                dataStream = response.GetResponseStream();
                reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                if (dataStream != null && reader != null && response != null)
                {
                    dataStream.Close();
                    reader.Close();
                    response.Close();
                }
                //Getting the response from the service
                //string result = responseFromServer.ToString();

            }

        }

另外,我不确定从该函数返回什么。 请帮忙。

【问题讨论】:

  • 这个概念是以你可以使用的格式返回你需要的数据。如果您要创建两个对话者,则此格式可以随心所欲。但是,存在一些大部分标准化的方法。查找“JSON”。
  • 无论您使用哪种语言或拥有多少应用程序都无关紧要。使用一个创建一个 RESTful api,并将其用作多个应用程序中的每个应用程序中的数据访问层。然后所有这些应用程序都可以使用此 api 相互集成并传递数据。

标签: c# php android mysql asp.net


【解决方案1】:

您的 php 文件是我所强调的“API”。
你基本上需要从你的 php 文件中返回它。

$vendorArray = [
    "Id" => $row["id"],
    "BusinessName" => $row["BusinessName"],
    // ... this is just pseudo code, convert the array or take the array or something like that
];

header('Content-type: application/json');
echo json_encode($vendorArray);

然后在 asp.net 中你这样做:

var deserializedVendor = JsonConvert.DeserializeObject<Vendor>(responseFromServer);

您的供应商类必须与您的 jsonObject 匹配才能反序列化

public class Vendor {

    public string Id {get;set;}

    public string BusinessName {get;set;}

    ...
}

这取决于你的 jsonResponse...

您还可以直接反序列化为具有如下供应商列表的复杂项目:

var allTheVendorsDeserialized = JsonConvert.DeserializeObject<AllTheVendors>(responseFromServer);


public class AllTheVendors {

    public bool Success {get;set}

    public List<Vendor> {get;set}

}

在哪里php:

$arr = ["Success" => true, $myArrayOfVendors];

header('Content-type: application/json');
echo json_encode($arr);

【讨论】:

    【解决方案2】:

    我相信,您的 PHP Web 应用程序是托管的,您可以通过以下步骤在 ASP.NET 中使用 PHP 服务:

    WebClient client = new WebClient(); //Create WebClient object
    
    string url = "http://test.com/test.php"; //Get the URL of the PHP service
    
    byte[] html = client.DownloadData(url); //Byte array to hold returned data from the service 
    

    最后使用UTF8Encoding对象将字节数组转换为sring:

    UTF8Encoding utf = new UTF8Encoding(); //Create an object of the UTF8Encoding class
    
    string str = utf.GetString(html); //Convert data into string 
    

    【讨论】:

    猜你喜欢
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 2018-01-13
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多