C#请求WebApi接口常用的两种方式
        
        作者:15726608245 · 2025-04-08 · 阅读时间:4分钟
    
    
    
          
     
    
        
        本文介绍了C#中请求WebApi接口的两种常用方式:WebRequest和HttpClient。WebRequest用于构建和管理HTTP请求,支持请求生命周期管理如重定向和超时设置。HttpClient是.NET中的现代化工具,支持异步操作、高并发场景,并提供灵活的请求配置和连接池管理。相比WebRequest,HttpClient更适合高性能应用开发。
    
    
        
    
     一、WebRequest方式引用dll
using System.IO;
using System.Net;
using System.Threading.Tasks;
//Post
public static string HttpPost(string url, string body)
{
    Encoding encoding = Encoding.UTF8;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";
    request.Accept = "text/html, application/xhtml+xml, */*";
    request.ContentType = "application/json";
    byte[] buffer = encoding.GetBytes(body);
    request.ContentLength = buffer.Length;
    request.GetRequestStream().Write(buffer, 0, buffer.Length);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
    {
        return reader.ReadToEnd();
    }
}
//GET
public static string HttpGet(string url)
{
    Encoding encoding = Encoding.UTF8;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "GET";
    request.Accept = "text/html, application/xhtml+xml, */*";
    request.ContentType = "application/json";
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
    {
        return reader.ReadToEnd();
    }
}WebRequest 核心概念与实现解析
WebRequest 是网络编程中用于处理HTTP/HTTPS请求的核心机制,其在不同开发环境和编程语言中存在多种实现形式。以下是主要分类及技术要点:
- 
WebRequest 的核心功能 - HTTP请求处理
- WebRequest 主要用于构建HTTP请求报文(包含请求行、请求头和请求体),并在服务端解析后存储于Request对象中,便于后续参数获取及业务处理。同时,通过Response对象设置响应数据,由服务器按HTTP协议格式返回客户端。
- 请求生命周期管理
- 
包括建立连接、处理重定向、超时控制等。例如,C#的HttpWebRequest支持设置 AllowAutoRedirect控制重定向, Timeout设定超时限制。 
 
二、HttpClient 方式
static HttpClient client = new HttpClient();
//根据 ID 获取产品
static async Task CreateProductAsync(Product product)
{
    HttpResponseMessage response = await client.PostAsJsonAsync(
    "api/products", product);
    response.EnsureSuccessStatusCode();
    // return URI of the created resource.
    return response.Headers.Location;
}
//创建新产品
static async Task GetProductAsync(string path)
{
    Product product = null;
    HttpResponseMessage response = await client.GetAsync(path);
    if (response.IsSuccessStatusCode)
    {
        product = await response.Content.ReadAsAsync();
    }
    return product;
}
//更新产品
static async Task UpdateProductAsync(Product product)
{
    HttpResponseMessage response = await client.PutAsJsonAsync(
    $"api/products/{product.Id}", product);
    response.EnsureSuccessStatusCode();
    // Deserialize the updated product from the response body.
    product = await response.Content.ReadAsAsync();
    return product;
}
//删除产品
static async Task DeleteProductAsync(string id)
{
    HttpResponseMessage response = await client.DeleteAsync(
    $"api/products/{id}");
    return response.StatusCode;
}HttpClient 异步调用
static async Task RunAsync()
{
    client.BaseAddress = new Uri("http://localhost:64195/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json"));
    try
    {
        Product product = new Product
        {
            Name = "Gizmo",
            Price = 100,
            Category = "Widgets"
        };
        var url = await CreateProductAsync(product);
        Console.WriteLine($"Created at {url}");
        // Get the product
        product = await GetProductAsync(url.PathAndQuery);
        ShowProduct(product);
        // Update the product
        Console.WriteLine("Updating price...");
        product.Price = 80;
        await UpdateProductAsync(product);
        // Get the updated product
        product = await GetProductAsync(url.PathAndQuery);
        ShowProduct(product);
        // Delete the product
        var statusCode = await DeleteProductAsync(product.Id);
        Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})");
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
    Console.ReadLine();
}C# HttpClient 核心功能与使用指南
HttpClient 是 .NET 中用于发送 HTTP 请求和接收响应的现代化工具,支持高性能、异步操作及灵活的配置。以下是其关键特性与使用要点:
- 
核心特性 - 
异步支持 
- 
所有方法均原生支持 async/await,适用于高并发场景(如微服务通信)。示例: var response = await client.GetAsync("https://api.example.com/data");
- 
连接池管理 
- 
每个 HttpClient实例维护独立的连接池,复用 TCP 连接以提升性能。 
- 
注意:避免频繁创建实例,推荐通过单例或 IHttpClientFactory管理。 
- 
请求配置 
- 
支持自定义请求头、超时时间、认证方式(如 Basic、JWT、Cookie)。示例(设置请求头): client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_jwt_token");
- 
数据传输格式 
- 
支持 JSON、表单、文件上传等格式,需通过 StringContent、 MultipartFormDataContent等类封装数据。 
 
- 
热门推荐
        一个账号试用1000+ API
            助力AI无缝链接物理世界 · 无需多次注册
            
        3000+提示词助力AI大模型
            和专业工程师共享工作效率翻倍的秘密
            
        热门API
- 1. AI文本生成
- 2. AI图片生成_文生图
- 3. AI图片生成_图生图
- 4. AI图像编辑
- 5. AI视频生成_文生视频
- 6. AI视频生成_图生视频
- 7. AI语音合成_文生语音
- 8. AI文本生成(中国)
最新文章
- 9个最佳Text2Sql开源项目:自然语言到SQL的高效转换工具
- 深入解析API网关策略:认证、授权、安全、流量处理与可观测性
- GraphQL API手册:如何构建、测试、使用和记录
- 自助式入职培训服务API:如何让企业管理更上一层楼?
- Python如何调用Jenkins API自动化发布
- 模型压缩四剑客:量化、剪枝、蒸馏、二值化
- 火山引擎如何接入API:从入门到实践的技术指南
- 为什么每个使用 API 的大型企业都需要一个 API 市场来增强其合作伙伴生态系统
- 构建更优质的API:2025年顶级API开发工具推荐 – Strapi
- 外部函数与内存API – Java 22 – 未记录
- FAPI 2.0 深度解析:下一代金融级 API 安全标准与实践指南
- .NET Core 下的 API 网关
热门推荐
                            一个账号试用1000+ API
                                助力AI无缝链接物理世界 · 无需多次注册