⼀、.Core WebAPI中的序列化
使⽤
Newtonsoft.Json
⾃定义全局配置处理:
public void ConfigureServices(IServiceCollection services)
{
//使⽤IMvcBuilder 配置Json序列化处理
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
});
}
⼆、Core WebAPI中的路由⽅法,
控制器路由:
[Route("api/C")]
Action
路由:
1.
根据
HttpMethod
路由
[HttpPut] 2.
根据
Template
模板路由
[HttpGet("{id}")]
Core WebAPI
中返回数据处理,提供了更 多的选择:
2.OKResult
,
OkObjectResult,
返回状态为
200 ;(注:⽤OkObjectResult
前台
jquery
⾃动解析为
object
对象不需要进⾏反序列化处理,
ContentResult
返回字符串 ;
JsonResult
返回
Json
对象,前台不需要反序列化处理;
3.
返回基础类型和引⽤类型 ,⾃动序列化,前台接收为
object
对象等;
三 、HttpMethod方式(举例学习一)
1.WebAPI各个功能模块的定义
/*
* API
定义如下
* GET api/C
获取菜单列表
* POST api/C
添加模块
* PUT api/C
修改模块
* PATCH api/C
修改菜单信息
* DELETE api/C
删除模块
*/
2.功能模块的后台逻辑代码 :
CModelContext _Context = new CModelContext();
/// <summary>
/// 获取列表
/// </summary>
/// <returns></returns>
[HttpGet]
public IEnumerable<C> Get()
{
List<C> list = _Context.C.ToList();
return list;
}
/// <summary>
/// 添加模块对象
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
[HttpPost]
public bool Add(Model m)
{
try
{
m.AddTime = DateTime.Now;
_Context.Model.Add(m);
_Context.SaveChanges();
return true;
}
catch (Exception ex){
return false;
}
}
/// <summary>
/// 修改模块
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
[HttpPut]
public bool Update(Model m)
{
try
{
Model oldModel = _Context.Model.Find(m.ModelId);
oldModel.ModelName = m.ModelName;
oldModel.SortNumber = m.SortNumber;
_Context.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 修改菜单对象
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
[HttpPatch]
public IActionResult Update(C m)
{
try
{
C oldC = _Context.MC.Find(m.CId);
if (oldC == null)
return NotFound("您要访问的菜单不存在或已经删除!");
oldC.CName = m.CName;
oldC.SortNumber = m.SortNumber;
oldC.ModelId = m.ModelId;
_Context.SaveChanges();
return Ok();
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
/// <summary>
/// 删除模块
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[HttpDelete]
public IActionResult Delete(string ids)
{
try
{
if (string.IsNullOrEmpty(ids))
throw new Exception("获取id参数失败");
List<int> idList = ids.Split(',').Select(q => Convert.ToInt32(q)).ToList();
List<Model> list = _Context.Model.Where(q => idList.Contains(q.ModelId)).ToList();
_Context.Model.RemoveRange(list);
int count = _Context.SaveChanges();
//⽤OkObjectResult 前台jquery⾃动解析为object对象不需要进⾏反序列化
return Ok(new
{
msg = $"总共删除{count}条数据!"
});
}
catch (Exception ex)
{
//使⽤ContentResult返回字符串处理
return Content(ex.Message);
}
}
3.jQuery ajax代码
function testOne() {
$.get(urlHelper.getApi('c'), {}, function (data) {
console.info(data);
var c1 = new Vue({
el: '#c1', data: {
result: data
}
});
})
}
testOne();
//添加菜单
var example2 = new Vue({
el: '#example-2',
data: {
name:'添加菜单'
},
//在 methods 对象中定义
methods: {
addC: function (event) {
//使⽤ Post提交新增
var _this = this;
this.name = '正在提交新增内容......';
$.post(urlHelper.getApi('c'), {
ModelName: '测试菜单5',
SortNumber:5
}, function (data) {
console.info(data);
_this.name = '提交成功';
});
},
updateModel: function (event) {
var _this = this;
$.ajax({
url: urlHelper.getApi('c'),
type: 'put',
data: {
ModelId: '4',
ModelName: '模块abc',
SortNumber: 4
},
success: function (data) {
console.info(data);
if (data == true)
alert('修改成功');
else alert('修改失败');
}
});
}
}
});
//修改菜单、删除模块
var btngroup1 = new Vue({
el: '#btngroup1',
data: {
name: '修改菜单',
name1: '删除模块'
},
methods: {
updateC: function (e) {
var _this = this;
//使⽤patch ⽅式修改菜单
$.ajax({
url: urlHelper.getApi('c'),
type:'patch',
data: {
CID: 1,
CName: '测试菜单One',
SortNumber: 100,
ModelID:2
},
success: function (data) {
console.info(data);
}
});
},
deleteC: function (e) {
//使⽤delete 提交⽅式删除模块
$.ajax({
url: urlHelper.getApi('c'),
type: 'delete',
data: {ids:[1003]
},
success: function (data) {
console.info(data);
},
error: function (data) {
console.info(data);
}
});
}
}
});
四、HttpMethod用法(举例学习二)
1.WebAPI功能方法含义
/*
* API
定义
* GET api/C/{id}
获取指定
ID
的菜单对象
* GET api/C/getmodel
获取模块列表内容
*/
2.Jquery
的
ajax
代码
//其他Get⽅式测试
var btngroup2 = new Vue({
el: '#btngroup2',
data: {
name: '获取菜单对象',
name1: '获取模块列表',
item: {}
},
methods: {
getMC: function (e) {
var _this = this;
//Api访问网址如 :http://localhost:8081/api/cc/1/
$.get(urlHelper.getApi('c','1'), { }, function (data) {
console.info(data);
_this.item = data;
});
},
getModel: function (e) {
var _this = this;
$.get(urlHelper.getApi('c', 'getmodel'), {}, function (data) {
console.info(data);
})
}
}
});
3.后台业务逻辑代码:
[HttpGet("{id}")]
public IActionResult Get(int ID)
{
C m = _Context.C.Find(ID);
if (m == null)
return NotFound();
return Json(m);
}
[HttpGet("getmodel")]
public IActionResult GetModel()
{
List<Model> list = _Context.Model.ToList();
return Json(list);
}