本文转自:http://mahedee.net/tag/web-api/

What is OData?

OData Stands for Open Data Protocol. It is a data access protocol for the web. OData provides a uniform way to query and manipulate data sets through CRUD operations (create, read, update, and delete). OData consumption can be done across different Programming Language. ASP.NET Web API supports both OData v3 and V4.

Advantages of OData Services

  • OData based on REST Architecture so we can retrieve data using URL
  • Support CRUD Operation using HTTP Method like GET, POST, PUT, DELETE
  • Support HTTP, JSON and Atom Pub
  • It is very light weight, so interaction of client and server is very fast

Disadvantage

  • Since it is URL based so many people think it is less secure
  • It does not support all type of custom query

Let’s implement OData Services using ASP.NET Web API

Tools and Technology used
I used following tools and technology to develop the project –

  • Visual Studio 2013
  • Visual C#
  • ASP.NET Web API 2
  • Entity Framework 6
  • Postman(Google postman)

Step 1: Create a ASP.net Web API Project
Open visual studio and then go
File -> Project -> ASP.NET Web Application

Now select Web API and press OK

Step 2: Install Microsoft.AspNet.Odata

To install OData Nuget Pacakge from Package Manager Console.
Select Tool -> NuGet Package Manager > Package Manager Console
Type following command in package manager console

PM> Install-Package Microsoft.AspNet.Odata

Step 3: Create a model name Employee

Create a Model name Employee in model folder

?
1
2
3
4
5
6
7
8
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Designation { get; set; }
    public string Dept { get; set; }
    public string BloodGroup { get; set; }
}

Step 4: Change or Add Connection String
Change or Add connection string in Web.config

?
1
2
<add name="DefaultConnection" connectionstring="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\HRMDB.mdf;Initial Catalog=HRMDB;Integrated Security=True" providername="System.Data.SqlClient">
</add>

Step 5: Create a Context class

?
1
2
3
4
5
6
7
8
9
10
Create HRMContext class in Model  folder.
    public class HRMContext : DbContext
    {
        public HRMContext()
            : base("DefaultConnection")
        {
        }
        public DbSet<Employee> Employees { get; set; }
    }

Step 6: Add a Controller

Press right button on Controller folder -> Add -> Controller

Now choose “Web API 2 OData v3 Controller with actions, using Entity Framework” scaffolding template and then press Add.

Now choose Controller Name as EmployeeController, Model name as Employee and Context name as HRMContext and click Add like below.

The following code will be generated on corresponding for the controller.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    public class EmployeeController : ODataController
    {
        private HRMContext db = new HRMContext();
        // GET: odata/Employee
        [EnableQuery]
        public IQueryable<Employee> GetEmployee()
        {
            return db.Employees;
        }
        // GET: odata/Employee(5)
        [EnableQuery]
        public SingleResult<Employee> GetEmployee([FromODataUri] int key)
        {
            return SingleResult.Create(db.Employees.Where(employee => employee.Id == key));
        }
        // PUT: odata/Employee(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta<employee> patch)
        {
            Validate(patch.GetEntity());
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            Employee employee = db.Employees.Find(key);
            if (employee == null)
            {
                return NotFound();
            }
            patch.Put(employee);
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return Updated(employee);
        }
        // POST: odata/Employee
        public IHttpActionResult Post(Employee employee)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            db.Employees.Add(employee);
            db.SaveChanges();
            return Created(employee);
        }
        // PATCH: odata/Employee(5)
        [AcceptVerbs("PATCH", "MERGE")]
        public IHttpActionResult Patch([FromODataUri] int key, Delta<employee> patch)
        {
            Validate(patch.GetEntity());
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            Employee employee = db.Employees.Find(key);
            if (employee == null)
            {
                return NotFound();
            }
            patch.Patch(employee);
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return Updated(employee);
        }
        // DELETE: odata/Employee(5)
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            Employee employee = db.Employees.Find(key);
            if (employee == null)
            {
                return NotFound();
            }
            db.Employees.Remove(employee);
            db.SaveChanges();
            return StatusCode(HttpStatusCode.NoContent);
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
        private bool EmployeeExists(int key)
        {
            return db.Employees.Count(e => e.Id == key) > 0;
        }
    }
</employee></employee>

Step 7: Configure OData End Point

Open the file App_Start/WebApiConfig.cs. Add the following using statements:

using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using Web.OData.Models;

Add the following code in the register method.

?
1
2
3
4
5
6
7
8
9
10
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<employee>("Employee");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
}
}
</employee>

Step 8: Enable Migration

Type the following command in package manager console to enable migration
PM> Enable-Migrations -ContextTypeName HRMContext

After pressing enter you will see a class name Configuration is created in Mingrations folder with some codes.

Step 9: Add seed data and add migration

Modify the Seed() method of Configuration class like below to add some seed data.

?
1
2
3
4
5
6
7
8
9
10
11
        protected override void Seed(Web.OData.Models.HRMContext context)
        {
            context.Employees.AddOrUpdate(
              p => p.Name,
              new Employee { Name = "Mahedee Hasan", Designation = "Software Architect", Dept = "SSD", BloodGroup = "A+" },
              new Employee { Name = "Kazi Aminur Rashid", Designation = "AGM", Dept = "SSD", BloodGroup = "NA" },
              new Employee { Name = "Tauhidul Haque", Designation = "DGM", Dept = "SSD", BloodGroup = "A+" }
            );
}

Now type the following command in the package manager console to add a migration.

PM> Add-Migration initialmigration

Step 10: Update database and attaché mdf file

Now type the following command in package manager console.

PM> Update-Database –Verbose

You will see two file .mdf and .ldf is created in your App_data directory. Now attached the file like below.

Now run you application. Run Postman. Type http://localhost:64126/odata/Employee in your postbox you will see following output in JSON format. Use port number on which your application currently running instead of 64126.

Now, it’s working…!! Cheers!!!

Download Source Code 

[转]Web API Introduction to OData Services using ASP.NET Web API相关推荐

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

    原文:Asp.Net Web API 2第十七课--Creating an OData Endpoint in ASP.NET Web API 2(OData终结点) 前言 很久没更新博客了,加上刚过 ...

  2. 基于.Net Framework 4.0 Web API开发(4):ASP.NET Web APIs 基于令牌TOKEN验证的实现

    概述:  ASP.NET Web API 的好用使用过的都知道,没有复杂的配置文件,一个简单的ApiController加上需要的Action就能工作.但是在使用API的时候总会遇到跨域请求的问题, ...

  3. 【Web API系列教程】1.1 — ASP.NET Web API入门

    前言 HTTP不仅仅服务于web页面,同时也是构建暴露服务和数据的API的强大平台.HTTP有着简单.灵活和无处不在的特点.你能想到的几乎所有平台都包含有一个HTTP库,所以HTTP服务可以遍及广泛的 ...

  4. ASP.NET Web Api OData

    ASP.NET Web API 2 Odata 基本使用 OData(开放数据协议)是一种ISO / IEC批准,OASIS标准定义的一组最佳实践用于构建和消费RESTful API中.OData 可 ...

  5. ASP.NET Web API的Controller是如何被创建的?

    Web API调用请求的目标是定义在某个HttpController类型中的某个Action方法,所以消息处理管道最终需要激活目标HttpController对象.调用请求的URI会携带目标HttpC ...

  6. ASP.NET Web API 控制器创建过程

    前言 本来这篇随笔应该是在上周就该写出来发布的,由于身体跟不上节奏感冒发烧有心无力,这种天气感冒发烧生不如死,也真正的体会到了什么叫病来如山倒,病去如抽丝.这两天状态才好了一点,让我理解了什么才是革命 ...

  7. ASP.NET Web API自身对CORS的支持:从实例开始

    在<通过扩展让ASP.NET Web API支持W3C的CORS规范>中我们通过自定义的HttpMessageHandler为ASP.NET Web API赋予了跨域资源共享的能力,具体来 ...

  8. ASP.NET MVC (四、ASP.NET Web API应用程序与跨域操作)

    目录 前言: 1.创建MVC项目 2.修改返回格式 3.创建[Web API]控制器 4.创建[HttpGet]访问接口 5.创建[HttpPost]访问接口 6.测试接口: 6.1.执行:点击[调试 ...

  9. 【ASP.NET Web API2】初识Web API

    Web Api 是什么? MSDN:ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务 百度百科:Web API是网络应用程序接口. ...

最新文章

  1. 嵌入式 Hi3515视频编码(H.264)笔记
  2. 实验5 函数程序设计 6-8 使用函数求最大公约数
  3. 倩女幽魂服务器维护时间,9月5日在线维护公告
  4. JAVA 算法练习(一)
  5. bzoj 3028 食物——生成函数
  6. UVA 1394 And Then There Was One 约瑟夫环数学方法
  7. 由数据范围反推算法时间复杂度和需要用到的算法类型
  8. informix 访问mysql_Informix 11.7 使用非系统用户访问数据库
  9. 微型计算机结构五大,微型计算机的体系结构
  10. iOS13新增SceneDelegate文件适配
  11. 07 巧算指数温度--参考即可不用算
  12. IJCAI-18 阿里妈妈搜索广告算法大赛亚军解决方案
  13. VUE报错rowserslist: caniuse-lite is outdated. Please run the following command: `npx browser
  14. 数据连接池contect.xml配置
  15. Android App links 链接打开app功能
  16. 整理:JavaScript 各种转型函数与类型转换细节
  17. Nodejs日志库winston配置
  18. ROS 机器人操作系统
  19. 返利网PHP面试_【返利网PHP面试】面试不算难 但是公司的办事奇怪-看准网
  20. 几种常见的编码格式 码表

热门文章

  1. 为什么ElasticSearch比MySQL更适合复杂条件搜索
  2. Lombok经常用,却不知道它的原理是什么
  3. 求求你别再用offset和limit分页了
  4. 面试官:你简历中写用过docker,能说说容器和镜像的区别吗?
  5. 9个让PyTorch模型训练提速的技巧!
  6. 豪取4个SOTA,谷歌魔改Transformer登NeurIPS 2021!一层8个token比1024个还好用
  7. 综述:如何给模型加入先验知识
  8. 2021谷歌学术指标出炉:CVPR总榜第4,仅次于Science,ECCV超过ICCV......
  9. 中国程序员开发的远程桌面火了!Mac 可用,只有 9MB,支持自建中继器
  10. 嫌弃YouTube推荐算法,这位小哥决定自己动手写代码来推荐视频