•  
  • E-mail:     sales@microtelesoft.com
  •  
  • Call Or WhatsApp Us. +91-9078673897 ,+91-8892654987 ,+91- 9090453772
  • Skype: bapi.mahapatra

Using MongoDB with Web API and ASP.NET Core


Published Date: 1/17/2018 3:06:39 AM

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.

app-design

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.

Note: A newer version of ASP.NET Core (v2) is now available. Read about it here www.dotnetcurry.com/aspnet/1402/aspnet-core-2-new-features

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

mongo-command

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

mongo-command-db

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

command-result

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

new-aspnet-app

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

new-webapi

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

add-api-controller

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:

result-json

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

composer-get

Click on Execute button and the following result will be displayed

fiddler-result

To Post the data, enter the following details in Fiddler

post-data

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

post-result

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.


Related Blogs on Software

1) eHospital Managment Systems Published Date : 10/31/2018
ERP Solutions for Hospital Management
2) Matrimonial Website Development Published Date : 10/31/2018
One of the fastest growing industries on the internet in India is online matrimonial portals.
3) Binary MLM Software Published Date : 10/31/2018
The MLM Binary Plan is a most popular plan among MLM companies, network marketers, part-timers and members who want to earn through MLM business
4) Property Management ERP Software Development Company in India Published Date : 02/07/2018
A property management system (PMS) can sometimes refer to an online program or software designed for residential or commercial property management. However, more often it refers to software used in the hospitality industry to manage the day to day requirements of running a hotel or resort. Some property management software can integrate with hospitality applications already running such as revenue and yield management programs, front/back office systems and point of sale systems, while other property management systems offer complete solutions by including all of these functions in their package.
5) Microtelesoft Pvt Ltd successfully presented Hospital Information Management System Published Date : 02/06/2018
Microtelesoft Pvt Ltd successfully presented Hospital Information Management System to Divisional Railway Hospital, Khurda on 06th February 2018.
6) Building Web applications with Knockout.js and ASP.NET core Published Date : 01/17/2018
Amongst all the client side frameworks backed by big companies, React.js and Angular.js appear to be the most popular. However, Knockout.js still maintains a good market share, thanks to its interesting peculiarities. Knockout is based on an MVVM paradigm similar to Angular.js, but unlike React.js. While it is adequate for modular complex applications, at the same time, it is very simple to mix with server side templating, similar to React.js, but unlike Angular.js.
7) What’s New for .NET Developers Published Date : 01/17/2018
Unless you have been living under a rock, you must have heard about .NET Standard and .NET Core by now. .NET Standard (http://www.dotnetcurry.com/dotnet/1377/dotnet-standard-2-xaml-standard) is a formal specification of .NET API’s that a Framework must implement to be .NET Standard compliant. This specification is important because it establishes a uniformity in the .NET ecosystem.
8) C# 7.1, 7.2 and 8 - New and Upcoming Features Published Date : 01/17/2018
Abstract: Visual Studio 2017 15.3 update was a big milestone for C#. It was the release vehicle for C# 7.1 – the first minor version of C# 7. This article will take a closer look at its new features and the plans for future versions (C# 8) of the language.
9) Using MongoDB with Web API and ASP.NET Core Published Date : 01/17/2018
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
10) Mozilla extends, and ends, Firefox support for Windows XP and Vista Published Date : 01/05/2018
Even Extended Support Releases will be naked and alone as of June 2018 Mozilla has announced it will end support for its Firefox browser on Windows XP and Windows Vista. The organisation offers Firefox Extended Support Releases (ESRs) that keep getting bug fixes for 54 weeks, even though nine new versions of Firefox should come along during that time. Mozilla offers ESR releases so that organisations with standard desktop environments can pick a version of Firefox and run it for a year, without the need to update their gold images.
11) Android banking Trojan may target Indian banks' mobile apps: Quick Heal Published Date : 01/05/2018
PUNE: Global IT security firm Quick Heal's Security Labs on Thursday announced it has spotted an Android Banking Trojan that imitates more than 232 mobile apps, including those offered by Indian banks like SBI, HDFC, ICICI, IDBI and Axis, among others. According to the researchers, the malware known as "Android.banker.A2f8a" is being distributed through a fake Flash Player app on third-party stores. After downloading the app, it keeps checking for the installed apps on the victim's device and particularly looks for the 232 banking and cryptocurrency apps.
12) Apple is updating its software to combat chip security holes Published Date : 01/05/2018
Apple said it has already released macOS and iOS updates to protect against the Meltdown vulnerability. Updates are forthcoming for Apple's Safari browser for macOS and iOS. Apple on Thursday said it will be releasing more software updates to protect against recently disclosed security vulnerabilities. This marked the first time that the company had made a formal statement about the Meltdown and Spectre vulnerabilities, which were reported to affect phones, servers andPCs.