本文转自:https://blogs.msdn.microsoft.com/webdev/2013/01/29/getting-started-with-asp-net-web-api-odata-in-3-simple-steps/

With the upcoming ASP.NET 2012.2 release, we’ll be adding support for OData to Web API. In this blog post, I’ll go over the three simple steps you’ll need to go through to get your first OData service up and running:

  1. Creating your EDM model
  2. Configuring an OData route
  3. Implementing an OData controller

Before we dive in, the code snippets in this post won’t work if you’re using the RC build. You can upgrade to using our latest nightly build by taking a look at this helpful blog post.

1) Creating your EDM model

First, we’ll create an EDM model to represent the data model we want to expose to the world. The ODataConventionModelBuilder class makes this this easy by using a set of conventions to reflect on your type and come up with a reasonable model. Let’s say we want to expose an entity set called Movies that represents a movie collection. In that case, we can create a model with a couple lines of code:

   1: ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();

   2: modelBuilder.EntitySet<Movie>("Movies");

   3: IEdmModel model = modelBuilder.GetEdmModel();

2) Configuring an OData route

Next, we’ll want to configure an OData route. Instead of using MapHttpRoute the way you would in Web API, the only difference here is that you use MapODataRoute and pass in your model. The model gets used for parsing the request URI as an OData path and routing the request to the right entity set controller and action. This would look like this:

   1: config.Routes.MapODataRoute(routeName: "OData", routePrefix: "odata", model: model);

The route prefix above is the prefix for this particular route. So it would only match request URIs that start with http://server/vroot/odata, where vroot is your virtual root. And since the model gets passed in as a parameter to the route, you can actually have multiple OData routes configured with a different model for each route.

3) Implementing an OData controller

Finally, we just have to implement our MoviesController to expose our entity set. Instead of deriving from ApiController, you’ll need to derive from ODataController. ODataController is a new base class that wires up the OData formatting and action selection for you. Here’s what an implementation might look like:

   1: public class MoviesController : ODataController

   2: {

   3:     List<Movie> _movies = TestData.Movies;

   4:  

   5:     [Queryable]

   6:     public IQueryable<Movie> GetMovies()

   7:     {

   8:         return _movies.AsQueryable();

   9:     }

  10:  

  11:     public Movie GetMovie([FromODataUri] int key)

  12:     {

  13:         return _movies[key];

  14:     }

  15:  

  16:     public Movie Patch([FromODataUri] int key, Delta<Movie> patch)

  17:     {

  18:         Movie movieToPatch = _movies[key];

  19:         patch.Patch(movieToPatch);

  20:         return movieToPatch;

  21:     }

  22: }

There’s a few things to point out here. Notice the [Queryable] attribute on the GetMovies method. This enables OData query syntax on that particular action. So you can apply filtering, sorting, and other OData query options to the results of the action. Next, we have the [FromODataUri] attributes on the key parameters. These attributes instruct Web API that the parameters come from the URI and should be parsed as OData URI parameters instead of as Web API parameters. Finally, Delta<T> is a new OData class that makes it easy to perform partial updates on entities.

One important thing to realize here is that the controller name, the action names, and the parameter names all matter. OData controller and action selection work a little differently than they do in Web API. Instead of being based on route parameters, OData controller and action selection is based on the OData meaning of the request URI. So for example if you made a request for http://server/vroot/odata/$metadata, the request would actually get dispatched to a separate special controller that returns the metadata document for the OData service. Notice how the controller name also matches the entity set name we defined previously. I’ll try to go into more depth about OData routing in a future blog post.

Instead of deriving from ODataController, you can also choose to derive from EntitySetController. EntitySetController is a convenient base class for exposing entity sets that provides simple methods you can override. It also takes care of sending back the right OData response in a variety of cases, like sending a 404 Not Found if an entity with a certain key could not be found. Here’s what the same implementation as above looks like with EntitySetController:

   1: public class MoviesController : EntitySetController<Movie, int>

   2: {

   3:     List<Movie> _movies = TestData.Movies;

   4:  

   5:     [Queryable]

   6:     public override IQueryable<Movie> Get()

   7:     {

   8:         return _movies.AsQueryable();

   9:     }

  10:  

  11:     protected override Movie GetEntityByKey(int key)

  12:     {

  13:         return _movies[key];

  14:     }

  15:  

  16:     protected override Movie PatchEntity(int key, Delta<Movie> patch)

  17:     {

  18:         Movie movieToPatch = _movies[key];

  19:         patch.Patch(movieToPatch);

  20:         return movieToPatch;

  21:     }

  22: }

Notice how you don’t need [FromODataUri] anymore because EntitySetController has already added it for you on its own action parameters. That’s just one of the several advantages of using EntitySetController as a base class.

Now that we have a working OData service, let’s try out a few requests. If you send a request to http://localhost/odata/Movies(2) with an “application/json” Accept header, you should get a response that looks like this:

   1: {

   2:   "odata.metadata": "http://localhost/odata/$metadata#Movies/@Element",

   3:   "ID": 2,

   4:   "Title": "Gladiator",

   5:   "Director": "Ridley Scott",

   6:   "YearReleased": 2000

   7: }

On the other hand, if you set an “application/atom+xml” Accept header, you might see a response that looks like this:

   1: <?xml version="1.0" encoding="utf-8"?>

   2: <entry xml:base="http://localhost/odata/" xmlns="http://www.w3.org/2005/Atom" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns:georss="http://www.georss.org/georss" xmlns:gml="http://www.opengis.net/gml">

   3:   <id>http://localhost/odata/Movies(2)</id>

   4:   <category term="MovieDemo.Model.Movie" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme" />

   5:   <link rel="edit" href="http://localhost/odata/Movies(2)" />

   6:   <link rel="self" href="http://localhost/odata/Movies(2)" />

   7:   <title />

   8:   <updated>2013-01-30T19:29:57Z</updated>

   9:   <author>

  10:     <name />

  11:   </author>

  12:   <content type="application/xml">

  13:     <m:properties>

  14:       <d:ID m:type="Edm.Int32">2</d:ID>

  15:       <d:Title>Gladiator</d:Title>

  16:       <d:Director>Ridley Scott</d:Director>

  17:       <d:YearReleased m:type="Edm.Int32">2000</d:YearReleased>

  18:     </m:properties>

  19:   </content>

  20: </entry>

As you can see, the Json.NET and DataContractSerializer-based responses you’re used to getting when using Web API controllers get replaced with the OData equivalents when you derive from ODataController.

[转]Getting started with ASP.NET Web API OData in 3 simple steps的更多相关文章

  1. node-odata: ASP.NET WEB API OData的替代品

    什么是 OData 协议? OData, 相信身为 .NET 程序员应该不为陌生, 尤其是它的实现: ASP.NET WEB API OData. 对于 OData, 官网上对其的定义是 OData ...

  2. 如何使用ASP.NET Web API OData在Oracle中使用Entity Framework 6.x Code-First方式开发 OData V4 Service

    环境: Visual Studio 2013 + .Net Framework 4.5.2 1.新建项目 2.安装OData,ODP.NET 安装的包: 下面是部分代码: using System; ...

  3. [转]Support Composite Key in ASP.NET Web API OData

    本文转自:https://code.msdn.microsoft.com/Support-Composite-Key-in-d1d53161 he default EntitySetControlle ...

  4. 杂项:ASP.NET Web API

    ylbtech-杂项:ASP.NET Web API ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务. ASP.NET Web A ...

  5. Asp.Net Web API 2第十七课——Creating an OData Endpoint in ASP.NET Web API 2(OData终结点)

    前言 很久没更新博客了,加上刚过年,现在准备重新开战,继续自己的学习之路.本文已同步到Web API2系列文章中http://www.cnblogs.com/aehyok/p/3446289.html ...

  6. Asp.Net Web Api 与 Andriod 接口对接开发经验,给小伙伴分享一下!

    最近一直急着在负责弄Asp.Net Web Api 与 Andriod 接口开发的对接工作! 刚听说要用Asp.Net Web Api去跟 Andriod 那端做接口对接工作,自己也是第一次接触Web ...

  7. 【ASP.NET Web API教程】2 创建各种Web API

    原文 [ASP.NET Web API教程]2 创建各种Web API Chapter 2: Creating Web APIs第2章 创建各种Web API 本文引自:http://www.asp. ...

  8. Asp.Net Web Api 与 Andriod 接口对接开发

    Asp.Net Web Api 与 Andriod 接口对接开发经验,给小伙伴分享一下!   最近一直急着在负责弄Asp.Net Web Api 与 Andriod 接口开发的对接工作! 刚听说要用A ...

  9. [转]ASP.NET Web API对OData的支持

    http://www.cnblogs.com/shanyou/archive/2013/06/11/3131583.html 在SOA的世界中,最重要的一个概念就是契约(contract).在云计算的 ...

随机推荐

  1. Jenkins+.Net Core+Git集成发布 - SkyMallCore快速开发平台

    准备工作:安装 Jenkins+java 直接百度安装,在此忽略 dotnet sdk(iis部署已经安装) 一:windows 部署到IIS 首先搭建IIS,站点应用程序池选择 ‘无托管代码’ 安装 ...

  2. C# 未安装Office环境下使用NPOI导出Excel文件

    1.NuGet直接安装NPOI程序包: 2. using NPOI.XSSF.UserModel; 3.导出Excel代码: private void TsbExport2ExcelClick(obj ...

  3. 常见的HTTP请求应答返回码列表

        200      OK 请求成功.一般用于GET与POST请求 300 Multiple Choices 多种选择.请求的资源可包括多个位置,相应可返回一个资源特征与地址的列表用于用户终端(例 ...

  4. 【Map,HashMap,Vector,List】资料汇总

    深入学习HashMap实现原理 http://www.cnblogs.com/xwdreamer/archive/2012/06/03/2532832.html 深入学习Vector原理 http:/ ...

  5. wireshark 1.10.0 编译 及 协议解析部分的一些变化

    wireshark不久前升级到1.10.0稳定版,这个版本正如其版本号一样,相比1.8.x有较大变化. 我们先说说在windows下编译的问题,1.8.4/1.8.6版本的编译见我的文章:http:/ ...

  6. 使用deque模块固定队列长度,用headq模块来查找最大或最小的N个元素以及实现一个优先级排序的队列

    一. deque(双端队列) 1. 使用 deque(maxlen=N)会新建一个固定大小的队列.当新的元素加入并且这个队列已满的时候,最老的元素会自动被移除掉 >>> from c ...

  7. 部署WSUS服务(一)

    引言:随着网络的发展,我们的生活也越来越离不开网络,但面临的安全威胁也越来越多.像去年爆发的针对Windows系统的勒索病毒(Wanna Cry)和年初爆发的Intel芯片漏洞告诉我们网络威胁时时刻刻 ...

  8. 使用go写一个简单的exe文件

    工作需要一个小工具给分析师用,原先打算写一个脚本的,但是呢我又不会用python,要写的话只能用java来实现(打包成可执行jar,使用java -jar 的命令来执行,当然得安装jdk).这种命令行 ...

  9. Flutter框架概览

    前言:进入新框架的开发前,有必要整体了解框架设计及特点,对该框架初步认识,此文对Flutter框架进行浅显梳理,以备查阅: Flutter框架   从该架构图可知,Flutter框架可分为Framew ...

  10. Universal-Image-Loader完全解析(下)

    Universal-Image-Loader完全解析(下) 在这篇文章中,我会继续跟大家分享有关于Universal-Image-Loader框架的相关知识,这次主要分享的是框架中图片缓存方面的知识. ...