如何用C#获取PHP对接MySQL接口返回的success与message值?
C# 调用远程用户验证接口并解析JSON响应
以下是使用.NET内置HttpClient调用你的PHP验证接口,并解析返回的success和message字段的示例代码:
1. 定义匹配响应结构的模型类
首先创建一个类来映射PHP返回的JSON结构,确保字段名称和类型与返回的JSON一致(若PHP返回小驼峰字段,可通过特性调整C#属性的映射关系):
public class AuthResponse { // 匹配JSON中的"success"字段 public bool Success { get; set; } // 匹配JSON中的"message"字段 public string Message { get; set; } }
2. 发送请求并解析响应
使用HttpClient发送POST请求(用户验证通常用POST),并解析JSON响应:
using System; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; using System.Collections.Generic; class AuthExample { static async Task Main(string[] args) { // 替换为你的PHP接口实际地址 string authApiUrl = "http://your-server-domain.com/your-auth-endpoint.php"; // 准备要提交的用户验证参数(根据PHP接口的参数要求调整键名) var requestData = new FormUrlEncodedContent(new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("username", "test_user"), new KeyValuePair<string, string>("password", "test_pass") }); using var httpClient = new HttpClient(); try { // 发送POST请求 HttpResponseMessage response = await httpClient.PostAsync(authApiUrl, requestData); // 确保请求未返回错误状态码 response.EnsureSuccessStatusCode(); // 读取响应的JSON字符串 string jsonResponse = await response.Content.ReadAsStringAsync(); // 解析JSON到模型对象 AuthResponse result = JsonSerializer.Deserialize<AuthResponse>(jsonResponse); // 使用解析后的结果 Console.WriteLine($"验证状态:{(result.Success ? "成功" : "失败")}"); Console.WriteLine($"返回消息:{result.Message}"); } catch (HttpRequestException ex) { Console.WriteLine($"网络请求错误:{ex.Message}"); } catch (JsonException ex) { Console.WriteLine($"JSON解析错误:{ex.Message}"); } } }
额外说明
- 如果你的PHP接口接受JSON格式的请求体(而非表单),可以替换请求内容为JSON格式:
// 构造JSON请求体 var userCredentials = new { username = "test_user", password = "test_pass" }; string jsonBody = JsonSerializer.Serialize(userCredentials); var requestContent = new StringContent(jsonBody, System.Text.Encoding.UTF8, "application/json"); // 发送请求 HttpResponseMessage response = await httpClient.PostAsync(authApiUrl, requestContent); - 若你习惯使用
Newtonsoft.Json(第三方JSON库),需要先通过NuGet安装Newtonsoft.Json包,然后将解析代码替换为:AuthResponse result = Newtonsoft.Json.JsonConvert.DeserializeObject<AuthResponse>(jsonResponse); - 确保你的项目引用了
System.Net.Http和System.Text.Json(或Newtonsoft.Json)命名空间。
内容的提问来源于stack exchange,提问作者Fatih Demir
相关产品推荐
相关产品推荐

