以下是一个使用 HttpClient 类的 C# 客户端调用示例:

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace WebApiTest
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // 创建 HttpClient 对象
            HttpClient client = new HttpClient();

            // 设置请求的 Content-Type 头为 application/json
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 构造请求内容
            string message = 'Hello, Web API!';
            StringContent content = new StringContent(message, System.Text.Encoding.UTF8, 'application/json');

            // 发送 POST 请求
            HttpResponseMessage response = await client.PostAsync('http://localhost:12345/api/mycontroller', content);

            // 处理响应结果
            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine(result);
            }
            else
            {
                Console.WriteLine('Error: {0}', response.StatusCode);
            }
        }
    }
}

其中,'http://localhost:12345/api/mycontroller' 是你的 Web API 接口的 URL。你需要根据实际情况修改该 URL。另外,你还需要将 message 参数的值替换为你想要传递的内容。

C# HttpClient 调用 Web API 接口传递参数示例

原文地址: https://www.cveoy.top/t/topic/mkhr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录