Skip to content

WebAPI Post 调用 WebAPI 并传递复杂类型

🏷️ WebAPI

WebAPI 代码:

cs
[HttpPost]
public string Test(Product product)
{
    return JsonConvert.SerializeObject(product);
}

public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

测试代码:

cs
HttpClient httpClient = new HttpClient();
Product product = new Product()
{
    ProductID = "003",
    ProductName = "旺仔牛奶",
    ProductCategory = "食品类"
};

string result = await httpClient.GetStringAsync("http://localhost:3849/api/Product/Get");
Console.WriteLine(result);

HttpResponseMessage postmsg = await httpClient.PostAsJsonAsync<Product>("http://localhost:3849/api/Product/Test", product);
string postResult = await postmsg.Content.ReadAsStringAsync();
Console.WriteLine(postResult);

输出结果:

js
["value1","value2"]
"{\"ProductID\":\"003\",\"ProductName\":\"旺仔牛奶\",\"ProductCategory\":\"
类\"}"