首页
/ 【亲测免费】 .NET 后台调用 WebAPI 指南

【亲测免费】 .NET 后台调用 WebAPI 指南

2026-01-26 06:11:47作者:宗隆裙

本文档旨在为.NET开发者提供详细指导,介绍如何在后台通过POST和GET方法调用Web API接口,同时涵盖文件上传的功能。无论是新手还是经验丰富的开发者,都能从中找到实用的信息来优化你的应用与服务间的通信过程。

简介

在现代软件开发中,Web API成为了不同系统之间数据交换的核心技术。.NET框架及.NET Core/ASP.NET Core提供了强大的支持来方便地实现客户端与服务器端的数据交互。本指南将分别展示使用HTTP GET和POST请求调用Web API的基本步骤,以及如何扩展到包含文件上传的情景。

GET方式调用WebAPI

GET请求通常用于从服务器检索信息,不涉及状态改变或数据修改。

示例代码

using System.Net;
using System.IO;

public string GetApiData(string apiUrl)
{
    var request = (HttpWebRequest)WebRequest.Create(apiUrl);
    request.Method = "GET";
    
    using (var response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode != HttpStatusCode.OK)
            throw new WebException("Error retrieving data.", null, WebExceptionStatus.ProtocolError, response);

        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }
}

POST方式调用WebAPI

POST请求常用于向服务器发送数据,如提交表单或上传文件。

示例代码

using System.IO;
using System.Net;
using System.Text;

public string PostApiData(string apiUrl, string jsonData)
{
    var request = (HttpWebRequest)WebRequest.Create(apiUrl);
    request.Method = "POST";
    request.ContentType = "application/json";

    byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
    request.ContentLength = byteArray.Length;

    using (Stream dataStream = request.GetRequestStream())
    {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode != HttpStatusCode.OK)
            throw new WebException("Error posting data.", null, WebExceptionStatus.ProtocolError, response);

        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            return reader.ReadToEnd();
        }
    }
}

文件上传到WebAPI

文件上传通常需要构造multipart/form-data类型的请求体。

示例代码

using System.IO;
using System.Net;
using System.Web;

public void UploadFileToApi(string apiUrl, string filePath)
{
    var fileContent = File.ReadAllBytes(filePath);
    var fileName = Path.GetFileName(filePath);

    var boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    var request = (HttpWebRequest)WebRequest.Create(apiUrl);
    request.Method = "POST";
    request.ContentType = "multipart/form-data; boundary=" + boundary;

    var bodyBuilder = new StringBuilder();
    bodyBuilder.Append("--").Append(boundary).Append("\r\n");
    bodyBuilder.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", fileName);
    bodyBuilder.Append("Content-Type: application/octet-stream\r\n\r\n");

    byte[] bodyHeader = Encoding.ASCII.GetBytes(bodyBuilder.ToString());

    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(bodyHeader, 0, bodyHeader.Length);
        requestStream.Write(fileContent, 0, fileContent.Length);
        requestStream.Write(Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"), 0, 25);
    }

    using (var response = (HttpWebResponse)request.GetResponse())
    {
        // 处理响应
    }
}

结论

通过上述示例,您现在应该能够理解和实施在.NET环境下,如何通过POST和GET方式调用来操作Web APIs,包括复杂的文件上传任务。这些基础但至关重要的技能将极大地提升您的应用程序与外界数据交互的能力。

请根据实际应用需求调整代码,并确保遵循最佳实践,以增强应用的安全性和性能。祝您编码愉快!

登录后查看全文
热门项目推荐
相关项目推荐