本文转自: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!!!

 

[转]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终结点)

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

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

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

  3. 基于.Net Framework 4.0 Web API开发(2):ASP.NET Web APIs 参数传递方式详解

    概述:  ASP.NET Web API 的好用使用过的都知道,没有复杂的配置文件,一个简单的ApiController加上需要的Action就能工作.调用API过程中参数的传递是必须的,本节就来谈谈 ...

  4. 基于.Net Framework 4.0 Web API开发(3):ASP.NET Web APIs 异常的统一处理Attribute 和统一写Log 的Attribute的实现

    概述:  ASP.NET Web API 的好用使用过的都知道,没有复杂的配置文件,一个简单的ApiController加上需要的Action就能工作.但是项目,总有异常发生,本节就来谈谈API的异常 ...

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

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

  6. 基于.Net Framework 4.0 Web API开发(5):ASP.NET Web APIs AJAX 跨域请求解决办法(CORS实现)

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

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

    前言 HTTP不仅仅服务于web页面.同一时候也是构建暴露服务和数据的API的强大平台.HTTP有着简单.灵活和无处不在的特点.你能想到的差点儿全部平台都包括有一个HTTP库.所以HTTP服务能够遍及 ...

  8. 用ASP创建API。NET Core (Day2):在ASP中创建API。网络核心

    下载PDF article - 1.5 MB 下载source - 152.4 KB 下载source - 206.3 KB 下载source code from GitHub 表的内容 中间件路线图 ...

  9. [转]ASP.NET web API 2 OData enhancements

    本文转自:https://www.pluralsight.com/blog/tutorials/asp-net-web-api-2-odata-enhancements Along with the ...

随机推荐

  1. 为微软ContosoUniversity例子加上学生自选课程计划

    把ContosoUniversity例子过了一遍,好象还是有很多东西未能理解,决定自己随便加个功能看可以自己完成不.... 从github的例子中clone下来ContosoUniversity项目, ...

  2. iOS检测项目图片资源是否包含P3图片

    1.问题描述 我们需要知道的是在iOS9.3以下系统上,.ipa包内如果含有p3图片,将会导致严重的闪退问题,具体原因还请google,非本文的重点. 2.问题解决 拿到的如果是ipa包(不是则跳过) ...

  3. [ActionScript 3.0] 通过BitmapData将对象保存成jpg图片

    此方法需要用到JPGEncoder.as和BitString.as这两个类,是将BitmapData对象转换成ByteArray,然后通过FileStream把此ByteArray写入到文件保存成jp ...

  4. centos6安装mysql5.7

    RPM包安装与卸载mysql 建议:装完mysql后立刻创建一个密码,不然下次登录的时候会有问题.原因是mysql 5.7会自动创建一个临时密码,过期失效,可以到grep "password ...

  5. The server of Nginx(二)——Nginx基本功能配置

    一.Nginx访问控制 (1)基于授权的访问控制 Nginx于Apache一样,可以实现基于用户授权的访问控制,当客户端要访问相应网站或者目录时要求输入用户名密码才能正常访问,配置步骤与Apache基 ...

  6. 浏览器性能接口performance.timing说明

    原文来自于 https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/NavigationTiming/Overview.html 下图描述了该接口的各个时间 ...

  7. js判断浏览器类型以及语言

    1.检查是否是移动端(Mobile).ipad.iphone.微信.QQ等 <script type="text/javascript"> //判断访问终端 var b ...

  8. [转] ScalaTest测试框架

    [From] https://blog.csdn.net/hany3000/article/details/51033610 ScalaTest测试框架 2016年04月01日 02:49:35 阅读 ...

  9. 剑指offer——面试题19:正则表达式匹配

    #include"iostream" using namespace std; bool MatchCore(char*str,char* pattern); bool Match ...

  10. 实现接口必须要加注解@Override吗

    不一定的,但是我们的编译器在查询我们重写的方法,方法名,参数,返回类型的时候,是能够根据注解来帮助我们判断方法重写的正确与否 所以我们有必要在编写过程中加上@Override,虽然我们的eclipse ...