后端调用WebApi

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using WebApplication4.Models;

namespace WebApplication4.Controllers
{
public class UsersController : Controller
{
//创建一个静态的只读的访问API的url
public static readonly Uri address = new Uri("https://localhost:44304/");
// GET: Users
public ActionResult Index()
{

return View();
}
public ActionResult FindUserListOne() {
//封装完整的API访问地址
Uri uri = new Uri(address, "/Valuse/GetUserList");
//定义一个客户端的Http请求
HttpClient httpClient = new HttpClient();
//使用请求地址发送get请求(以异步操作将get请求发送给指定的url)
var response = httpClient.GetAsync(uri).Result;
string user = "";
//判断
if (response.IsSuccessStatusCode)
{
//API和客户端不在同一工程,跨域访问,返回的是json串
user = response.Content.ReadAsStringAsync().Result.ToString();
ViewData["user"] = user;

//WebApi和客户端在同一工程(注意:后台访问Api需要下载并引用System.Net.Http.Formatting.dll后才会有response.Content.ReadAsAsync方法)
User us = response.Content.ReadAsAsync<User>().Result;
List<User> list = response.Content.ReadAsAsync<List<User>>().Result;
ViewData["list"] = list;
}
//return Json(user,JsonRequestBehavior.AllowGet);
return View();
}
}
}

原文地址:https://www.cnblogs.com/ypyp123/p/13252829.html