web api 2 学习笔记 (OData Batch request)
之前介绍过OData 中实现RPC的写法,今天在来一个批量操作。
参考 : https://damienbod.wordpress.com/2014/08/14/web-api-odata-v4-batching-part-10/
http://www.odata.org/getting-started/advanced-tutorial/
public static void Register(HttpConfiguration config)
{
DefaultODataBatchHandler odataBatchHandler = new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer);
odataBatchHandler.MessageQuotas.MaxOperationsPerChangeset = ;
odataBatchHandler.MessageQuotas.MaxPartsPerBatch = ;
config.MapODataServiceRoute("odata", "api", GetModel(), odataBatchHandler);
}
填入DefaultODataBatchHandler就可以了.
前端js
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:4274/api/$batch", true);
xhr.setRequestHeader("Content-Type", "multipart/mixed; boundary=batch_ebdc0b88-eeb1-4dd6-b170-74331f39bd03");
xhr.setRequestHeader("OData-Version", "4.0");
xhr.setRequestHeader("singleTransaction", "true"); var body = [];
//POST
body.push('--batch_ebdc0b88-eeb1-4dd6-b170-74331f39bd03');
body.push('Content-Type: multipart/mixed; boundary=changeset_54ac09ec-f437-4b08-9925-fd42ed7bd58f');
body.push('');
body.push('--changeset_54ac09ec-f437-4b08-9925-fd42ed7bd58f');
body.push('Content-Type: application/http');
body.push('Content-Transfer-Encoding: binary');
body.push('Content-ID: 1');
body.push('');
body.push('POST http://localhost:4274/api/products HTTP/1.1');
body.push('OData-Version: 4.0');
body.push('Content-Type: application/json;odata.metadata=minimal');
body.push('Accept: application/json;odata.metadata=minimal');
body.push('');
body.push('{"code":"mk100"}');
body.push('--changeset_54ac09ec-f437-4b08-9925-fd42ed7bd58f--'); //PUT
body.push('--batch_ebdc0b88-eeb1-4dd6-b170-74331f39bd03');
body.push('Content-Type: multipart/mixed; boundary=changeset_2346da5e-88c9-4aa5-a837-5db7e1368147');
body.push('');
body.push('--changeset_2346da5e-88c9-4aa5-a837-5db7e1368147');
body.push('Content-Type: application/http');
body.push('Content-Transfer-Encoding: binary');
body.push('Content-ID: 2');
body.push('');
body.push('PUT http://localhost:4274/api/products(1) HTTP/1.1');
body.push('OData-Version: 4.0');
body.push('Content-Type: application/json;odata.metadata=minimal');
body.push('Accept: application/json;odata.metadata=minimal');
body.push('');
body.push('{"id":1,"code":"mk100"}');
body.push('--changeset_2346da5e-88c9-4aa5-a837-5db7e1368147--'); //DELETE
body.push('--batch_ebdc0b88-eeb1-4dd6-b170-74331f39bd03');
body.push('Content-Type: multipart/mixed; boundary=changeset_2346da5e-88c9-4aa5-a837-5db7e1368142');
body.push('');
body.push('--changeset_2346da5e-88c9-4aa5-a837-5db7e1368142');
body.push('Content-Type: application/http');
body.push('Content-Transfer-Encoding: binary');
body.push('Content-ID: 3');
body.push('');
body.push('DELETE http://localhost:4274/api/products(1) HTTP/1.1');
body.push('OData-Version: 4.0');
body.push('Content-Type: application/json;odata.metadata=minimal');
body.push('Accept: application/json;odata.metadata=minimal');
body.push('');
body.push('--changeset_2346da5e-88c9-4aa5-a837-5db7e1368142--'); //GET
body.push('--batch_ebdc0b88-eeb1-4dd6-b170-74331f39bd03');
body.push('Content-Type: application/http');
body.push('Content-Transfer-Encoding: binary');
body.push('Content-ID: 4');
body.push('');
body.push('GET http://localhost:4274/api/products HTTP/1.1');
body.push('OData-Version: 4.0');
body.push('Content-Type: application/json;odata.metadata=minimal');
body.push('Accept: application/json;odata.metadata=minimal');
body.push(''); body.push('--batch_ebdc0b88-eeb1-4dd6-b170-74331f39bd03--');
body.push('');
var data = body.join("\r\n");
xhr.send(data);
从上面代码可以看出,我们所有的请求需要通过一个大请求来包装,把所有的小请求用string写进大请求的body就可以了。
需要特别注意的事string的格式,连空行都是非常重要的哦!
参考 http://www.odata.org/documentation/odata-version-3-0/batch-processing/
虽然这是v3的但是可以看一下, 2.2 Batch Request Body
请求分2中,一种叫changeset,一种叫 operation
changeset 是指那些会改变资源的请求(e.g. POST,PUT,DELETE,ACTION), operation 是指不会改变资源的请求 (e.g. GET,FUNCTION)
代码中可以看出来,这2种写法会有不同。
通常我们在做批量操作时希望会有transaction
这时我们可以扩展 DefaulODataBatchHandle
public class ODataBatchHandlerSingleTransaction : DefaultODataBatchHandler
{
public ODataBatchHandlerSingleTransaction(HttpServer httpServer)
: base(httpServer)
{
} public async override Task<IList<ODataBatchResponseItem>> ExecuteRequestMessagesAsync(IEnumerable<ODataBatchRequestItem> requests,CancellationToken cancellation)
{
if (requests == null) { throw new ArgumentNullException("requests"); }
IList<ODataBatchResponseItem> responses = new List<ODataBatchResponseItem>(); try
{
using (DB db = new DB())
{
using (DbContextTransaction trans = db.Database.BeginTransaction())
{
foreach (ODataBatchRequestItem request in requests)
{
var changeSetResponse = (ChangeSetResponseItem)await request.SendRequestAsync(Invoker, cancellation);
responses.Add(changeSetResponse);
}
bool isAllOk = responses.All(response => ((ChangeSetResponseItem)(response)).Responses.All(r => r.IsSuccessStatusCode));
if (isAllOk)
{
trans.Commit();
}
else
{
trans.Rollback();
}
}
}
}
catch
{
foreach (ODataBatchResponseItem response in responses)
{
if (response != null)
{
response.Dispose();
}
}
throw;
}
return responses;
}
}
拦截以后我们就可以在这一层创建 database Context 和 transaction , controller 内就可以通过任何方式来获取到这里的 context 来做使用.
比如可以使用 Request.Items 来保存传值. (注 : httpRequest 和 httpRequestMessage 是不同的,我们在controller使用的是 message 哦)
还有一点要特别注意的是,如果你需要transaction就不应该有请求,因为GET 请求会在 ExecuteRequestMessagesAsync 之后才执行,如果这时我们释放掉了 database context 那么就会有问题了.
web api 2 学习笔记 (OData Batch request)的更多相关文章
- web api 2 学习笔记 (Odata ODataQueryOptions 使用)
[ODataRoutePrefix("products")] public class ProductController : BaseController { [ODataRou ...
- Rest API 开发 学习笔记(转)
Rest API 开发 学习笔记 概述 REST 从资源的角度来观察整个网络,分布在各处的资源由URI确定,而客户端的应用通过URI来获取资源的表示方式.获得这些表徵致使这些应用程序转变了其状态.随着 ...
- abp学习(四)——根据入门教程(aspnetMVC Web API进一步学习)
Introduction With AspNet MVC Web API EntityFramework and AngularJS 地址:https://aspnetboilerplate.com/ ...
- Web Api系列教程第2季(OData篇)(二)——使用Web Api创建只读的OData服务
前言 很久没更新了,之前有很多事情,所以拖了很久,非常抱歉.好了,废话不多说,下面开始正题.本篇仍然使用上一季的的项目背景(系列地址http://www.cnblogs.com/fzrain/p/34 ...
- JavaSE中线程与并行API框架学习笔记——线程为什么会不安全?
前言:休整一个多月之后,终于开始投简历了.这段时间休息了一阵子,又病了几天,真正用来复习准备的时间其实并不多.说实话,心里不是非常有底气. 这可能是学生时代遗留的思维惯性--总想着做好万全准备才去做事 ...
- [转]Web Api系列教程第2季(OData篇)(二)——使用Web Api创建只读的OData服务
本文转自:http://www.cnblogs.com/fzrain/p/3923727.html 前言 很久没更新了,之前有很多事情,所以拖了很久,非常抱歉.好了,废话不多说,下面开始正题.本篇仍然 ...
- 《ASP.NET MVC4 WEB编程》学习笔记------Web API 续
目录 ASP.NET WEB API的出现缘由 ASP.NET WEB API的强大功能 ASP.NET WEB API的出现缘由 随着UI AJAX 请求适量的增加,ASP.NET MVC基于Jso ...
- 《ASP.NET MVC4 WEB编程》学习笔记------Web API
本文截取自情缘 1. Web API简单说明 近来很多大型的平台都公开了Web API.比如百度地图 Web API,做过地图相关的人都熟悉.公开服务这种方式可以使它易于与各种各样的设备和客户端平台集 ...
- Asp.net core 学习笔记 ( OData )
2018-12-10 更新 : 从前我都是把 entity 直接用于 odata 曝露 api 给程序用. 如果这个程序是我们自己写的前端,这样的方式非常好,因为就好比前端可以直接对数据库每一个表做操 ...
随机推荐
- 关于Android API的理解
举个例子: 比如程序中用到了android.content.ClipboardManager这个类, 而该类是在API 11才添加到 “库”. (原谅我,不理解Google API 文档里的 adde ...
- Java高级特性之枚举学习总结
在Java SE5之前,我们要使用枚举类型时,通常会使用static final 定义一组int常量来标识,代码如下 public static final int MAN = 0; public s ...
- c# 根据自定义Attribute排序
add a class: public class ExportAttribute : Attribute { public int FieldOrder { get; set; } ...
- ubuntu 下操作文件夹,出现Permission denied的解决的方法
今天遇到个诡异问题,向一个文件夹(myResources)粘贴文件的时候,出现这样一个提示 Permission denied 是权限没设好,仅仅是拷贝粘贴一个文件,怎么会这样? 解决的办法: $ s ...
- HDU1159 && POJ1458:Common Subsequence(LCS)
Problem Description A subsequence of a given sequence is the given sequence with some elements (poss ...
- 【移动开发】WIFI热点通信(二)
相信大家在上一篇中已经了解了Android中WIFI热点通信的相关操作知识(http://smallwoniu.blog.51cto.com/3911954/1536126),今天我们将在上一篇代码基 ...
- 关于js跨域
get方式: 称为jsonp,就是js的跨域通信方式,因为知道有些标签可以跨域获取内容,例如img,script,link...,jsonp就是把动态创建一个script标签,然后配置src属性,后台 ...
- centos6 Cacti部署文档
centos6 Cacti部署文档 1.安装依赖 yum -y install mysql mysql-server mysql-devel httpd php php-pdo php-snmp ph ...
- mui实现自动登录
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name= ...
- C#学习(三)
通过类创建对象的过程称为类的实例化 匿名类型提供了一种方便的方法,可用来将一组只读属性封装到单个对象中,而无需首先显式定义一个类型. 要将匿名类型或包含匿名类型的集合作为参数传递给某一方法,可将参数作 ...