开放数据协议 (OData) 是一种用于 web 的数据访问协议
OData 提供统一的方式来查询和操作数据集通过 CRUD 操作 (创建、 读取、 更新和删除)
以下以asp .net为例作讲解
Server:向已存在的asp .net 项目中添加web api
引用
Microsoft.AspNet.WebApi
Microsoft.AspNet.WebApi.Client
Microsoft.AspNet.WebApi.Cors
Microsoft.AspNet.WebApi.WebHost
在App_Start中添加类文件WebApiConfig.cs
public class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
修改Global.asax.cs文件,注入WebApiConfig
//在注册默认路由之前 before registering the default Web Application route as that would otherwise take precedence.
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
参考资料
OData定义web api
分Server和Client两部分
Server
配置
ODataModelBuilder builder = new ODataConventionModelBuilder();
//多个实体,不能重名
builder.EntitySet<Product>("Products");
builder.EntitySet<Supplier>("Suppliers");
//定义自定义方法
builder.Function("GetSalesTaxRate")
.Returns<double>()
.Parameter<int>("PostalCode");
configuration.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
实现相关接口
完成之后,运行or发布Server,保证能够访问
Client
新建控制台(任意客户端)
安装工具(需要重启VS)
新建服务代理
配置服务代理:打开.tt文件,如图所示,有一个MetadataDocumentUri参数,配置为Server的网址,保存之后,会自动生成服务代理(更新也是这个步骤)
调用服务
string serviceUri = "http://localhost:5003/";
var container = new Default.Container(new Uri(serviceUri));
//调用自定义方法
var rate = container.GetSalesTaxRate(1);
示例代码
https://github.com/zLulus/NotePractice/tree/dev3/Website/DotNetFramework/NotePractice
https://github.com/zLulus/NotePractice/tree/dev3/Website/DotNetFramework/OData.Client
参考资料
https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint
https://docs.microsoft.com/zh-cn/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-client-app
http://www.cnblogs.com/bluedoctor/p/4384659.html