[转]Web API Introduction to OData Services using ASP.NET Web API

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

时间: 2024-10-15 19:16:32

[转]Web API Introduction to OData Services using ASP.NET Web API的相关文章

【Web API系列教程】2.2 — ASP.NET Web API中的路由和动作选择机制

这篇文章描述了ASP.NET Web API如何将HTTP请求路由到控制器上的特定动作. 备注:想要了解关于路由的高层次概述,请查看Routing in ASP.NET Web API. 这篇文章侧重于路由过程的细节.如果你创建了一个Web API项目并且发现一些请求并没有按你预期得到相应的路由,希望这篇文章有所帮助. 路由有以下三个主要阶段: 将URI匹配到路由模板 选择一个控制器 选择一个动作 你可以用自己的习惯行为来替换其中一些过程.在本文中,我会描述默认行为.在结尾,我会指出你可以自定义

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

概述:  ASP.NET Web API 的好用使用过的都知道,没有复杂的配置文件,一个简单的ApiController加上需要的Action就能工作.但是在使用API的时候总会遇到跨域请求的问题, 特别各种APP万花齐放的今天,对API使用者身份角色验证是不能避免的(完全开发的API不需要对使用者身份角色进行管控,可以绕过),这篇文章就来谈谈基于令牌TOKEN身份验证的实现. 问题: 对于Web API的选择性的开放,使用者无论使用AJAX,还是HttpClient对接,总要对使用者的身份角色

【Web API系列教程】2.1 — ASP.NET Web API中的路由机制

这篇文章描述了ASP.NET Web API如何将HTTP请求发送(路由)到控制器. 备注:如果你对ASP.NET MVC很熟悉,你会发现Web API路由和MVC路由非常相似.主要区别是Web API使用HTTP方法来选择动作(action),而不是URI路径.你也可以在Web API中使用MVC风格的路由.这篇文章不需要ASP.NET MVC的任何知识. 路由表 在ASP.NET Web API中,控制器是一个用于处理HTTP请求的类.控制器中的公共方法被称为动作方法或简单动作.当Web A

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

概述:  ASP.NET Web API 的好用使用过的都知道,没有复杂的配置文件,一个简单的ApiController加上需要的Action就能工作.但是在使用API的时候总会遇到跨域请求的问题,特别各种APP万花齐放的今天,API的跨域请求是不能避免的. 在默认情况下,为了防止CSRF跨站的伪造攻击(或者是 javascript的同源策略(Same-Origin Policy)),一个网页从另外一个域获取数据时就会收到限制.有一些方法可以突破这个限制,那就是大家熟知的JSONP, 当然这只是

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

概述:  ASP.NET Web API 的好用使用过的都知道,没有复杂的配置文件,一个简单的ApiController加上需要的Action就能工作.但是项目,总有异常发生,本节就来谈谈API的异常的统一处理和写统一写log逻辑的解决方案. 问题: 在ASP.NET Web API编写时,如果每个API都写异常处理逻辑,不但加大了开发工作量,且每个开发人员处理异常返回的数据结构也不尽相同,在异常发生情况下,客户端处理异常的逻辑就不再通用,也同时加大了对接接口人员的工作量,好的API错误码和错误

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

前言 HTTP不仅仅服务于web页面.同一时候也是构建暴露服务和数据的API的强大平台.HTTP有着简单.灵活和无处不在的特点.你能想到的差点儿全部平台都包括有一个HTTP库.所以HTTP服务能够遍及广泛的client,包括浏览器.移动设备和传统桌面应用程序. ASP.NET Web API是一个在.NET框架上构建web API的框架.在本教程中,你将使用ASP.NET Web API来创建一个返回产品列表的web API. 创建Web API项目 在本教程中,你将使用ASP.NET Web

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

概述:  ASP.NET Web API 的好用使用过的都知道,没有复杂的配置文件,一个简单的ApiController加上需要的Action就能工作.调用API过程中参数的传递是必须的,本节就来谈谈API使用过程中参数的传递方式. 各种参数传递方式的实现: ASP.NET Web API参数有两种传递方式,一种是请求时携带QueryString,对应API 开发中的FromUrlAttribute属性,也是参数传递默认属性,并且每个API可以含有多个此类型的参数,主要应对GET请求,但此种方式

[转]ASP.NET web API 2 OData enhancements

本文转自:https://www.pluralsight.com/blog/tutorials/asp-net-web-api-2-odata-enhancements Along with the release of Visual Studio 2013 came a new release of ASP.NET MVC (called MVC 5) and ASP.NET Web API (called Web API 2). Part of the enhancements to the

[转]Using $select, $expand, and $value in ASP.NET Web API 2 OData

本文转自:https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/using-select-expand-and-value by Mike Wasson+ Web API 2 adds support for the $expand, $select, and $value options in OData. These options allow a client to