新建mvc项目
然后新增UserController,代码如下
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
namespace consumingAPI.Controllers
{
public class UserController : Controller
{
Uri baseAddress = new Uri("https://jsonplaceholder.typicode.com/todos/1");
HttpClient client;
public UserController()
{
client = new HttpClient();
client.BaseAddress = baseAddress;
}
public ActionResult Index()
{
string data = "";
HttpResponseMessage response = client.GetAsync(client.BaseAddress + "").Result;
if (response.IsSuccessStatusCode)
{
data = response.Content.ReadAsStringAsync().Result;
}
return Content(data);
}
}
}
其他地方不需要修改,项目结构如下:
运行得到结果:
与postman返回结果一致。