使用HttpClient调用Web Api的示例代码如下:
using System;
using SendPlanConsole;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Net;
// See https://aka.ms/new-console-template for more information
var plan= new PlanDto{PlanId = Guid.NewGuid().ToString(),PlanName="Test",PlanDescription="Test plan"};
var content= JsonConvert.SerializeObject(plan);
var url="http://localhost:5197/ApprovePlan/SaveInputPlan";
using(var client=new HttpClient())
{
HttpContent httpContent = new StringContent(content);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpContent.Headers.ContentType.CharSet = "utf-8";
HttpResponseMessage responseMessage = await client.PostAsync(url, httpContent);
Console.WriteLine(await responseMessage.Content.ReadAsStringAsync());
}
Console.WriteLine(plan.ToString());
这里需要注意的是名称空间,需要使用System.Net,然后是Headers.ContentType 的设置,类型为MediaTypeHeaderValue,名称空间为System.Net.Http.Headers,这里需要设置为application/json,Api端的代码如下:
[HttpPost("SaveInputPlan")]
public string SaveInputPlan(PlanDto plan)
{
var content = JsonConvert.SerializeObject(plan);
System.IO.File.WriteAllText("InputPlans/" + plan.PlanId + ".json", content);
return "";
}
网友评论