在C#前端开发场景中,调用接口是实现前后端数据交互的关键环节,无论是桌面应用还是基于特定框架的前端项目,都需要通过接口获取或提交数据。目前主流的接口调用方式包括HttpClient和WebRequest两类,开发者可以根据项目需求选择合适的方案。

一、使用HttpClient调用接口
HttpClient是.NET Framework 4.5及以上版本提供的HTTP客户端工具,相比传统方式更轻量、易用,支持异步操作,是目前推荐使用的接口调用方案。
1. 发送GET请求
GET请求通常用于从接口获取数据,不需要携带请求体,参数一般拼接在URL后面。
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建HttpClient实例
using (HttpClient client = new HttpClient())
{
try
{
// 拼接请求URL,这里使用ipipp.com作为示例域名
string url = "https://ipipp.com/api/user/list?page=1&size=10";
// 发送GET请求并获取响应
HttpResponseMessage response = await client.GetAsync(url);
// 确保响应成功
response.EnsureSuccessStatusCode();
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("接口返回数据:" + responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("请求发生异常:" + e.Message);
}
}
}
}
2. 发送POST请求
POST请求通常用于向接口提交数据,需要设置请求体,常见的请求体格式有JSON、表单数据等。
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
try
{
string url = "https://ipipp.com/api/user/add";
// 构造JSON格式的请求参数
string jsonParam = "{"name":"张三","age":25,"email":"test@ipipp.com"}";
// 设置请求内容类型为JSON
StringContent content = new StringContent(jsonParam, Encoding.UTF8, "application/json");
// 发送POST请求
HttpResponseMessage response = await client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("接口返回数据:" + responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine("请求发生异常:" + e.Message);
}
}
}
}
二、使用WebRequest调用接口
WebRequest是更早的HTTP请求抽象类,兼容性更好,支持更老版本的.NET框架,不过使用起来相对繁琐一些。
1. 发送GET请求
using System;
using System.IO;
using System.Net;
class Program
{
static void Main(string[] args)
{
string url = "https://ipipp.com/api/user/detail?id=1";
// 创建WebRequest实例
WebRequest request = WebRequest.Create(url);
// 设置请求方法为GET
request.Method = "GET";
try
{
// 获取响应
using (WebResponse response = request.GetResponse())
{
// 读取响应流
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream))
{
string responseBody = reader.ReadToEnd();
Console.WriteLine("接口返回数据:" + responseBody);
}
}
}
}
catch (WebException e)
{
Console.WriteLine("请求发生异常:" + e.Message);
}
}
}
2. 发送POST请求
using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main(string[] args)
{
string url = "https://ipipp.com/api/user/update";
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
// 构造表单格式的参数
string postData = "id=1&name=李四&age=26";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// 设置请求内容类型
request.ContentType = "application/x-www-form-urlencoded";
// 设置请求内容长度
request.ContentLength = byteArray.Length;
// 写入请求体
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
try
{
using (WebResponse response = request.GetResponse())
{
using (Stream respStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(respStream))
{
string responseBody = reader.ReadToEnd();
Console.WriteLine("接口返回数据:" + responseBody);
}
}
}
}
catch (WebException e)
{
Console.WriteLine("请求发生异常:" + e.Message);
}
}
}
三、接口调用的注意事项
- HttpClient建议全局复用,不要每次请求都创建新的实例,避免端口耗尽问题。
- 请求和响应过程需要做好异常捕获,处理网络异常、接口返回错误状态码等情况。
- 如果接口需要身份认证,需要在请求头中添加对应的认证信息,比如Token、Cookie等。
- 传递敏感参数时,建议使用HTTPS协议,避免数据在传输过程中被窃取。
- 对于返回的数据,需要根据接口定义的格式进行解析,比如JSON格式可以使用Newtonsoft.Json等库进行反序列化。
四、两种方案的选择建议
如果是.NET Framework 4.5及以上版本的项目,优先选择HttpClient,它支持异步操作,代码更简洁,性能也更好。如果是需要兼容老版本.NET框架的项目,可以选择WebRequest方案。另外如果项目中需要调用大量接口,还可以对HttpClient进行封装,统一处理请求头、超时设置、响应解析等通用逻辑,减少重复代码。
C#接口调用HttpClientWebRequestAPI请求修改时间:2026-07-24 07:36:33