文档库 最新最全的文档下载
当前位置:文档库 › mvc4跨域调用WEBAPI传递JSON数据

mvc4跨域调用WEBAPI传递JSON数据

一、WEBAPI
public ActionResult getJson()
{
return Json("Json来了!", JsonRequestBehavior.AllowGet);
}

二、调用WEBAPI
using https://www.wendangku.net/doc/df12110279.html,.Http;
using https://www.wendangku.net/doc/df12110279.html,.Http.Headers;
using System.Web;
using System.Web.Mvc;

public ActionResult Index()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:2238/");

// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("Home/getJson" ).Result; // Blocking call(阻塞调用)!

if (response.IsSuccessStatusCode)
{
ViewBag.json = response.Content.ReadAsStringAsync().Result;

}
return View();
}

相关文档