WebApi的ajax呼叫以及HttpClient的跨域呼叫
前言
兩種網路服務:
WebService:基於SOAP風格的網路服務,使用方法進行請求
WebAPI:基於REST風格的網路服務,使用資源進行請求
5個方法:查一個,查所有,增加,修改,刪除
使用
《1》js的非同步(缺點:不能跨域)
《2》HttpClient
WebApi
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using t3_Models;
namespace t3_WebAPI.Controllers
{
public class UserInfoController : ApiController
{
// GET api/userinfo
//使用Method=Get的方式請求url=api/userinfo,則這個方法會被呼叫執行
//查詢所有資訊
public IEnumerable<UserInfo> Get()
{
List<UserInfo> list=new List<UserInfo>();
list.Add(new UserInfo()
{
Id = 1,
Name = "clx"
});
list.Add(new UserInfo()
{
Id = 2,
Name = "gj"
});
list.Add(new UserInfo()
{
Id = 3,
Name = "hr"
});
list.Add(new UserInfo()
{
Id = 4,
Name = "hqg"
});
return list;
}
// GET api/userinfo/5
//查詢單條資訊
public string Get(int id)
{
return "value";
}
// POST api/userinfo
//增加
//public void Post(string value)
//{
//}
[HttpPost]
public void Add(string value)
{
}
// PUT api/userinfo/5
//修改
[HttpPut]
public void Put(int id, string value)
{
}
// DELETE api/userinfo/5
//刪除
[HttpDelete]
public void Delete(int id)
{
}
}
}
HttpClient跨域呼叫
建立並初始化物件:
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
讀集合:
HttpResponseMessage response = client.GetAsync(url).Result;
var userList = response.Content.ReadAsAsync<IEnumerable<資料型別>>().Result;
根據編號讀物件
HttpResponseMessage response1 = client.GetAsync(url).Result;
var userInfo = response1.Content.ReadAsAsync<資料型別>().Result;
增加:
HttpResponseMessage response = client.PostAsJsonAsync(“api/userinfo”, userInfo).Result;
使用response.IsSuccessStatusCode判斷是否成功
使用response.Content.ToString()獲取返回值
修改:
HttpResponseMessage response = client.PutAsJsonAsync(“api/userinfo/”+userInfo.UserId, userInfo).Result;
使用response.IsSuccessStatusCode判斷是否成功
使用response.Content.ToString()獲取返回值
刪除:
HttpResponseMessage response = client.DeleteAsync(“api/userinfo/” + uid).Result;
使用response.IsSuccessStatusCode判斷是否成功
使用response.Content.ToString()獲取返回值
using System.Net;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Mvc;
using t3_Models;
namespace t3_Client.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
//客戶端物件的建立與初始化
HttpClient client=new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//執行Get操作
HttpResponseMessage response= client.GetAsync("http://localhost:2460/api/userinfo").Result;
var list= response.Content.ReadAsAsync<List<UserInfo>>().Result;
ViewData.Model = list;
return View();
}
}
}
model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace t3_Models
{
public partial class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
}
}
獲取到model後寫入html中
@using t3_Models
@model List<t3_Models.UserInfo>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table border="1">
<tr>
<th>編號</th>
<th>姓名</th>
</tr>
@foreach (UserInfo userInfo in Model)
{
<tr>
<td>@userInfo.Id</td>
<td>@userInfo.Name</td>
</tr>
}
</table>
</div>
</body>
</html>
ajax請求
指定請求的資料型別: contentType: “application/json; charset=utf-8”,//資料型別
主要的屬性:
type:請求方式,包括Get、Post、Put、Delete
url:請求資源,根據路由規則編寫
data:請求資料,為json格式
contentType:請求資料的型別及編碼
dataType:返回的資料型別,可以是text、json
success:成功處理的回撥函式
備註中為修改請求的示例
注意:使用js的非同步操作,不可以跨域訪問
var data = ‘{“UserId”:"’ + $(’#userId’).val() +
‘",“UserName”:"’ + $(’#userName’).val() + ‘"}’;
$.ajax({
type: 'PUT',//請求型別。get,post,put,delete
url: 'api/UserInfo/' + $('#userId').val(),//請求地址
data: data,//引數
contentType: "application/json; charset=utf-8",//資料型別
dataType: 'text',//返回資料型別
success: function (msg) {
if (eval(msg) == '1') {
InitData();
}
}
});
<script>
$(function() {
LoadList();
});
function LoadList() {
$.ajax({
type: 'get',//請求方式,可以為Get,Post,Put,Delete
data: '{}',//傳送的引數
url: 'http://localhost:2460/api/userinfo',//請求地址
contentType: "application/json; charset=utf-8",//資料型別
dataType: 'json',
success: function(list) {
var list1 = $('#list');
list1.empty();
$.each(list, function(index, item) {
list1.append('<tr><td>' + item.Id + '</td><td>' + item.Name + '</td></tr>');
});
}
});
}
</script>