MongoDB is a NoSQL document-oriented database that allows you to define JSON based documents which are schema independent. The schema can be mapped with Tables in a Relational Database. A schema in MongoDB is called as collection, and a record in this schema is called as document

Download an ASP.NET MVC CMS - Free Trial

In open source modern web applications, the use of a NoSQL database is gaining popularity due to its non-relational behavior. In this demo, we will create a Web API using ASP.NET Core which will perform CRUD Operations on a collection. The following diagram explains the implementation of the application.

The advantage of a Web API is that it can be used as HTTP services and can be subscribed by any client application ranging from Desktop to Mobiles. Using Web API as a medium, these client apps can easily interact with a NoSQL database like MongoDB.

Web API and MongoDB - The Implementation

We need MongoDB for creating collections and storing documents in it. MongoDB can be downloaded from this link. Install the database. Once the installation is over, the system drive will create a MongoDB folder in the following path

C:\Program Files\MongoDB

We also need to create a data folder where the data will be stored. On my machine I have created E:\MongoDbData\data

Open the Command prompt and navigate to the following folder

C:\Program Files\MongoDB\Server\3.2\bin

and run the command as shown in the following image

This will connect to MongoDB on port 27017.

Open another instance of the command prompt and navigate to the bin folder and run the following command

This will connect to the default test database. Run the following command on > (command prompt)

> use EmployeeDB

This will create a database of name EmployeeDB if it does not exist already, else it will be opened for transactions if the database already exists. In this database we can create transaction using the following command

db.createCollection('Products')

The Schema for the Products collection can be defined using following command from the command prompt

db.Products.insert({'ProductId':1,'ProductName':'Desktop All in One','Price':43000,'Category':'Electronics'})

Run the following command

>db.Products.find({})

The following result will be displayed

The schema will add _id property. This property will be an ObjectId which will be generated automatically.

Now since the database and collection is ready, we can create a Web API application. Please visit this link to read about creating Web API using MVC 6.

Creating the MongoDB Application

We will be using Visual Studio 2015 for creating this application. We need to install ASP.NET Core which can be downloaded from this link.

Step 1: Open Visual studio and create a new ASP.NET Web Application as shown in the following image

Name this application as MVC6_WEBAPI_MongoDB. Click on the OK button which will open the following window which shows ASP.NET Templates. Select Web API as shown in the following image

This will create a Web API project.

Step 2: Open the project.json file and in the dependencies section, add the following package dependency:

"mongocsharpdriver": "2.3.0"

Save the project and the Mongo CSharp driver will be installed for the project.

Step 3: In the project add the Models folder, in this add a new class file of name Product.cs. Add the following code in this file

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
 
namespace MVC6_WEBAPI_MongoDB.Models
{
    public class Product
    {
        public ObjectId Id { get; set; }
        [BsonElement("ProductId")]
        public int ProductId { get; set; }
        [BsonElement("ProductName")]
        public string ProductName { get; set; }
        [BsonElement("Price")]
        public int Price { get; set; }
        [BsonElement("Category")]
        public string Category { get; set; }
    }
}

The class contains Id property of the type ObjectId. This property is mandatory so that the CLR object can be mapped with Collection in MongoDB. The class contains properties having the BsonElement attribute applied on it. This represent the mapped property with the MongoDB collection.

Step 3: Add the DataAccess.cs class file in the Models folder with the following code in it

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System.Collections.Generic;
 
namespace MVC6_WEBAPI_MongoDB.Models
{
    public class DataAccess
    {
        MongoClient _client;
        MongoServer _server;
        MongoDatabase _db;
 
        public DataAccess()
        {
            _client = new MongoClient("mongodb://localhost:27017");
            _server = _client.GetServer();
            _db = _server.GetDatabase("EmployeeDB");     
        }
 
        public IEnumerable<Product> GetProducts()
        {
            return _db.GetCollection<Product>("Products").FindAll();
        }
 
 
        public Product GetProduct(ObjectId id)
        {
            var res = Query<Product>.EQ(p=>p.Id,id);
            return _db.GetCollection<Product>("Products").FindOne(res);
        }
 
        public Product Create(Product p)
        {
            _db.GetCollection<Product>("Products").Save(p);
            return p;
        }
 
        public void Update(ObjectId id,Product p)
        {
            p.Id = id;
            var res = Query<Product>.EQ(pd => pd.Id,id);
            var operation = Update<Product>.Replace(p);
            _db.GetCollection<Product>("Products").Update(res,operation);
        }
        public void Remove(ObjectId id)
        {
            var res = Query<Product>.EQ(e => e.Id, id);
            var operation = _db.GetCollection<Product>("Products").Remove(res);
        }
    }
}

The above code uses the following classes:

MongoServer - This represents an instance of the MongoDB Server.

MongoClient - This class is used to read the server instance for performing operations on the database. The constructor of this class is passed with the MongoDB Connection string as shown in the following box

"mongodb://localhost:27017"

MongoDatabase - This represents Mongo Database for performing operations. This class provides following methods

  • GetCollection<T>(collection)
  • · T is the CLR object to be collection.
  • · This returns MongoCollection.
  • Methods
  • FindAll() - Returns all documents in collection()
  • FindOne() - Returns a single document based on Mongo Query object generated based on _id.
  • Save() - Save a new document in collection.
  • Update() - Update a document.
  • Remove() - Remove a document.

The above code uses all these methods for performing CRUD operations.

Step 4: We will register the DataAccess class in the Dependency Injection feature provided by the ASP.NET Core. To do this open the Start.cs file and add the following line in ConfigureServices() method

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<DataAccess>();
    services.AddMvc();
}

Step 5: In the Controllers folder, add a new Web API Controller class of name ProductAPIController as shown in the following image

In this class add the following code

using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
 
using MVC6_WEBAPI_MongoDB.Models;
using MongoDB.Bson;
 
namespace MVC6_WEBAPI_MongoDB.Controllers
{
    [Route("api/Product")]
    public class ProductAPIController : Controller
    {
        DataAccess objds;
 
        public ProductAPIController()
        {
            objds = d;
        }
 
        [HttpGet]
        public IEnumerable<Product> Get()
        {
            return objds.GetProducts();
        }
        [HttpGet("{id:length(24)}")]
        public IActionResult Get(string id)
        {
            var product = objds.GetProduct(new ObjectId(id));
            if (product == null)
            {
                return NotFound();
            }
            return new ObjectResult(product);
        }
 
        [HttpPost]
        public IActionResult Post([FromBody]Product p)
        {
            objds.Create(p);
            return new HttpOkObjectResult(p);
        }
        [HttpPut("{id:length(24)}")]
        public IActionResult Put(string id, [FromBody]Product p)
        {
            var recId = new ObjectId(id);
            var product = objds.GetProduct(recId);
            if (product == null)
            {
                return HttpNotFound();
            }
            
            objds.Update(recId, p);
            return new OkResult();
        }
 
        [HttpDelete("{id:length(24)}")]
        public IActionResult Delete(string id)
        {
            var product = objds.GetProduct(new ObjectId(id));
            if (product == null)
            {
                return NotFound();
            }
 
            objds.Remove(product.Id);
            return new OkResult();
        }
    }
}

The above Web API class uses DataAccess class for performing CRUD operations. The Web API class contains GET, POST, PUT and DELETE methods for Http operations.

Step 5: Open the launchSettings.json in the Properties folder and add the following settings in it:

"profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/Product",
      "environmentVariables": {
        "Hosting:Environment": "Development"
      }
    }

This provides launchUrl to run the application in IIS Express.

Run the application in browser and the following result will be displayed:

To Test this we will make use of Fiddler tool. Open the fiddler tool and enter the following URL in it

Click on Execute button and the following result will be displayed

To Post the data, enter the following details in Fiddler

Click on Execute button and the data will be posted. Run the following command from the Mongo Command prompt

>db.Products.find({})

The following result will be displayed

Conclusion: Using Mongo C# Driver we can easily connect to the popular MongoDB database and perform CRUD operations. Using ASP.NET WebAPI,  MongoDB data can be easily made available to various client apps for storing and reading data.

Download the source code of this article (Github)

Using MongoDB with Web API and ASP.NET Core的更多相关文章

  1. 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】

    Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...

  2. 【翻译】使用Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定

    原文地址:http://www.dotnetjalps.com/2013/05/Simple-data-binding-with-Knockout-Web-API-and-ASP-Net-Web-Fo ...

  3. Asp.Net Web API VS Asp.Net MVC

    http://www.dotnet-tricks.com/Tutorial/webapi/Y95G050413-Difference-between-ASP.NET-MVC-and-ASP.NET-W ...

  4. ASP.NET Web API和ASP.NET Web MVC中使用Ninject

    ASP.NET Web API和ASP.NET Web MVC中使用Ninject 先附上源码下载地址 一.准备工作 1.新建一个名为MvcDemo的空解决方案 2.新建一个名为MvcDemo.Web ...

  5. Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定

    使用Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定   原文地址:http://www.dotnetjalps.com/2013/05/Simple-da ...

  6. Web API 2 入门——使用Web API与ASP.NET Web窗体(谷歌翻译)

    在这篇文章中 概观 创建Web窗体项目 创建模型和控制器 添加路由信息 添加客户端AJAX 作者:Mike Wasson 虽然ASP.NET Web API与ASP.NET MVC打包在一起,但很容易 ...

  7. 004.Create a web app with ASP.NET Core MVC using Visual Studio on Windows --【在 windows上用VS创建mvc web app】

    Create a web app with ASP.NET Core MVC using Visual Studio on Windows 在 windows上用VS创建mvc web app 201 ...

  8. Web API 基于ASP.NET Identity的Basic Authentication

    今天给大家分享在Web API下,如何利用ASP.NET Identity实现基本认证(Basic Authentication),在博客园子搜索了一圈Web API的基本认证,基本都是做的Forms ...

  9. 在ASP.NET Web API和ASP.NET Web MVC中使用Ninject

    先附上源码下载地址 一.准备工作 1.新建一个名为MvcDemo的空解决方案 2.新建一个名为MvcDemo.WebUI的空MVC应用程序 3.使用NuGet安装Ninject库   二.在ASP.N ...

随机推荐

  1. 在Ubuntu上快速搭建基于Beego的RESTful API

    最近在研究Go,打算基于Go做点Web API,于是经过初步调研,打算用Beego这个框架,然后再结合其中提供的ORM以及Swagger的集成,可以快速搭建一个RESTful API的网站. 下面是具 ...

  2. 面试笔记--Fast-Fail(快速失败)机制

    1.解决: fail-fast机制,是一种错误检测机制.它只能被用来检测错误,因为JDK并不保证fail-fast机制一定会发生.若在多线程环境下使用fail-fast机制的集合,建议使用“java. ...

  3. BZOJ 5467 Slay the Spire

    BZOJ 5467 Slay the Spire 我的概率基础也太差了.jpg 大概就是这样,因为强化牌至少翻倍,所以打出的牌必定是全部的强化牌或者$k-1$个强化牌,然后剩余的机会打出最大的几个攻击 ...

  4. 晓晨高效IP提取工具 附源码

    在网上找的几个代理ip网站,抓取下来的.解析网页用的是HtmlAgilityPack,没有用正则.自己重写了ListView使他动态加载的时候不闪烁.效果图 下载地址:http://files.cnb ...

  5. Linq to XML操作XML文件

    LINQ的类型 在MSDN官方文件中,LINQ分为几种类型: . LINQ to Objects(或称LINQ to Collection),这是LINQ的基本功能,针对集合对象进行查询处理,包括基本 ...

  6. MySQL表结构变更,不可不知的Metadata Lock

    在线上进行DDL操作时,相对于其可能带来的系统负载,其实,我们最担心的还是MDL其可能导致的阻塞问题. 一旦DDL操作因获取不到MDL被阻塞,后续其它针对该表的其它操作都会被阻塞.典型如下,如阻塞稍久 ...

  7. Mysql乱码问题总结

    这两天研究了下Mysql的字符集编码和排序规则,有个很典型的问题就是乱码问题.所以小记一下. http://www.jianshu.com/p/4c6a27542df4 http://blog.csd ...

  8. 解析vue2.0的diff算法 虚拟DOM介绍

    react虚拟dom:依据diff算法台 前端:更新状态.更新视图:所以前端页面的性能问题主要是由Dom操作引起的,解放Dom操作复杂性 刻不容缓 因为:Dom渲染慢,而JS解析编译相对非常非常非常快 ...

  9. 【kindle笔记】之 《鬼吹灯》-9-20

    [kindle笔记]读书记录-总 9-20 日常吐槽 连着几天,基本是一口气读完了鬼吹灯. 想来,也算是阴差阳错了.本来是想看盗墓的,读了几页开头,心想坏了,拷贝错了,这是鬼吹灯-- 讲真的,每每读小 ...

  10. mysql cpu 100% 满 优化方案

    解决MySQL CPU占用100%的经验总结 - karl_han的专栏 - CSDN博客 https://blog.csdn.net/karl_han/article/details/5630782 ...