前言
两种网络服务:
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>