c# 给webapi接口 public HttpResponseMessage PostFromBody string message方法传递参数的客户端调用例子
以下是一个使用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参数的值替换为你想要传递的内容。
原文地址: http://www.cveoy.top/t/topic/ZRs 著作权归作者所有。请勿转载和采集!