This tutorial creates a web API that performs Create, Read, Update, and Delete (CRUD) operations on a MongoDB NoSQL database.
In this tutorial, you learn how to:
- Configure MongoDB
- Create a MongoDB database
- Define a MongoDB collection and schema
- Perform MongoDB CRUD operations from a web API
- Customize JSON serialization
Prerequisites
- .NET Core SDK 2.2
- Visual Studio 2019 with the ASP.NET and web development workload
- MongoDB
- I suggest Visual Studio Code
Configure MongoDB
If using Windows, MongoDB is installed at C:\Program Files\MongoDB by default. Add C:\Program Files\MongoDB\Server\\bin to the
Path environment variable. This change enables MongoDB access from anywhere on your development machine.
Use the mongo Shell in the following steps to create a database, make collections, and store documents. For more information on mongo Shell commands, see Working with the mongo Shell.
- Choose a directory on your development machine for storing the data. For example, C:\BooksData on Windows. Create the directory if it doesn't exist. The mongo Shell doesn't create new directories.
- Open a command shell. Run the following command to connect to MongoDB on default port 27017. Remember to replace
with the directory you chose in the previous step.consolemongod --dbpath - Open another command shell instance. Connect to the default test database by running the following command:console
mongo - Run the following in a command shell:console
use BookstoreDbIf it doesn't already exist, a database named BookstoreDb is created. If the database does exist, its connection is opened for transactions. - Create a
Bookscollection using following command:consoledb.createCollection('Books')The following result is displayed:console{ "ok" : 1 } - Define a schema for the
Bookscollection and insert two documents using the following command:consoledb.Books.insertMany([{'Name':'Design Patterns','Price':54.93,'Category':'Computers','Author':'Ralph Johnson'}, {'Name':'Clean Code','Price':43.15,'Category':'Computers','Author':'Robert C. Martin'}])The following result is displayed:console{ "acknowledged" : true, "insertedIds" : [ ObjectId("5bfd996f7b8e48dc15ff215d"), ObjectId("5bfd996f7b8e48dc15ff215e") ] }NoteThe ID's shown in this article will not match the IDs when you run this sample. - View the documents in the database using the following command:console
db.Books.find({}).pretty()The following result is displayed:console{ "_id" : ObjectId("5bfd996f7b8e48dc15ff215d"), "Name" : "Design Patterns", "Price" : 54.93, "Category" : "Computers", "Author" : "Ralph Johnson" } { "_id" : ObjectId("5bfd996f7b8e48dc15ff215e"), "Name" : "Clean Code", "Price" : 43.15, "Category" : "Computers", "Author" : "Robert C. Martin" }The schema adds an autogenerated_idproperty of typeObjectIdfor each document.
The database is ready. You can start creating the ASP.NET Core web API.
Create the ASP.NET Core web API project
- Go to File > New > Project.
- Select the ASP.NET Core Web Application project type, and select Next.
- Name the project BooksApi, and select Create.
- Select the .NET Core target framework and ASP.NET Core 2.2. Select the API project template, and select Create.
- Visit the NuGet Gallery: MongoDB.Driver to determine the latest stable version of the .NET driver for MongoDB. In the Package Manager Console window, navigate to the project root. Run the following command to install the .NET driver for MongoDB:PowerShell
Install-Package MongoDB.Driver -Version {VERSION}
Add an entity model
- Add a Models directory to the project root.
- Add a
Bookclass to the Models directory with the following code:C#using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace BooksApi.Models { public class Book { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("Name")] public string BookName { get; set; } public decimal Price { get; set; } public string Category { get; set; } public string Author { get; set; } } }In the preceding class, theIdproperty:- Is required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
- Is annotated with [BsonId] to designate this property as the document's primary key.
- Is annotated with [BsonRepresentation(BsonType.ObjectId)] to allow passing the parameter as type
stringinstead of an ObjectId structure. Mongo handles the conversion fromstringtoObjectId.
TheBookNameproperty is annotated with the [BsonElement] attribute. The attribute's value ofNamerepresents the property name in the MongoDB collection.
Add a configuration model
- Add the following database configuration values to appsettings.json:JSON{ "BookstoreDatabaseSettings": { "BooksCollectionName": "Books", "ConnectionString": "mongodb://localhost:27017", "DatabaseName": "BookstoreDb" }, "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } } }
- Add a BookstoreDatabaseSettings.cs file to the Models directory with the following code:C#
namespace BooksApi.Models { public class BookstoreDatabaseSettings : IBookstoreDatabaseSettings { public string BooksCollectionName { get; set; } public string ConnectionString { get; set; } public string DatabaseName { get; set; } } public interface IBookstoreDatabaseSettings { string BooksCollectionName { get; set; } string ConnectionString { get; set; } string DatabaseName { get; set; } } }The precedingBookstoreDatabaseSettingsclass is used to store the appsettings.json file'sBookstoreDatabaseSettingsproperty values. The JSON and C# property names are named identically to ease the mapping process. - Add the following highlighted code to
Startup.ConfigureServices:C#public void ConfigureServices(IServiceCollection services) { services.Configure( Configuration.GetSection(nameof(BookstoreDatabaseSettings))); services.AddSingleton (sp => sp.GetRequiredService >().Value); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } In the preceding code:- The configuration instance to which the appsettings.json file's
BookstoreDatabaseSettingssection binds is registered in the Dependency Injection (DI) container. For example, aBookstoreDatabaseSettingsobject'sConnectionStringproperty is populated with theBookstoreDatabaseSettings:ConnectionStringproperty in appsettings.json. - The
IBookstoreDatabaseSettingsinterface is registered in DI with a singleton service lifetime. When injected, the interface instance resolves to aBookstoreDatabaseSettingsobject.
- The configuration instance to which the appsettings.json file's
- Add the following code to the top of Startup.cs to resolve the
BookstoreDatabaseSettingsandIBookstoreDatabaseSettingsreferences:C#using BooksApi.Models;
Add a CRUD operations service
- Add a Services directory to the project root.
- Add a
BookServiceclass to the Services directory with the following code:C#using BooksApi.Models; using MongoDB.Driver; using System.Collections.Generic; using System.Linq; namespace BooksApi.Services { public class BookService { private readonly IMongoCollection_books; public BookService(IBookstoreDatabaseSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _books = database.GetCollection (settings.BooksCollectionName); } public List Get() => _books.Find(book => true).ToList(); public Book Get(string id) => _books.Find(book => book.Id == id).FirstOrDefault(); public Book Create(Book book) { _books.InsertOne(book); return book; } public void Update(string id, Book bookIn) => _books.ReplaceOne(book => book.Id == id, bookIn); public void Remove(Book bookIn) => _books.DeleteOne(book => book.Id == bookIn.Id); public void Remove(string id) => _books.DeleteOne(book => book.Id == id); } } In the preceding code, anIBookstoreDatabaseSettingsinstance is retrieved from DI via constructor injection. This technique provides access to the appsettings.json configuration values that were added in the Add a configuration model section. - Add the following highlighted code to
Startup.ConfigureServices:C#public void ConfigureServices(IServiceCollection services) { services.Configure( Configuration.GetSection(nameof(BookstoreDatabaseSettings))); services.AddSingleton (sp => sp.GetRequiredService >().Value); services.AddSingleton (); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } In the preceding code, theBookServiceclass is registered with DI to support constructor injection in consuming classes. The singleton service lifetime is most appropriate becauseBookServicetakes a direct dependency onMongoClient. Per the official Mongo Client reuse guidelines,MongoClientshould be registered in DI with a singleton service lifetime. - Add the following code to the top of Startup.cs to resolve the
BookServicereference:C#using BooksApi.Services;
The
BookService class uses the following MongoDB.Driver members to perform CRUD operations against the database:- MongoClient – Reads the server instance for performing database operations. The constructor of this class is provided the MongoDB connection string:C#public BookService(IBookstoreDatabaseSettings settings) { var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _books = database.GetCollection
(settings.BooksCollectionName); } - IMongoDatabase – Represents the Mongo database for performing operations. This tutorial uses the generic GetCollection
(collection) method on the interface to gain access to data in a specific collection. Perform CRUD operations against the collection after this method is called. In theGetCollectionmethod call:(collection) collectionrepresents the collection name.TDocumentrepresents the CLR object type stored in the collection.
GetCollection(collection) returns a MongoCollection object representing the collection. In this tutorial, the following methods are invoked on the collection:- DeleteOne – Deletes a single document matching the provided search criteria.
- Find
– Returns all documents in the collection matching the provided search criteria. - InsertOne – Inserts the provided object as a new document in the collection.
- ReplaceOne – Replaces the single document matching the provided search criteria with the provided object.
Add a controller
Add a
BooksController class to the Controllers directory with the following code:
C#
using BooksApi.Models;
using BooksApi.Services;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace BooksApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BooksController : ControllerBase
{
private readonly BookService _bookService;
public BooksController(BookService bookService)
{
_bookService = bookService;
}
[HttpGet]
public ActionResult> Get() =>
_bookService.Get();
[HttpGet("{id:length(24)}", Name = "GetBook")]
public ActionResult Get(string id)
{
var book = _bookService.Get(id);
if (book == null)
{
return NotFound();
}
return book;
}
[HttpPost]
public ActionResult Create(Book book)
{
_bookService.Create(book);
return CreatedAtRoute("GetBook", new { id = book.Id.ToString() }, book);
}
[HttpPut("{id:length(24)}")]
public IActionResult Update(string id, Book bookIn)
{
var book = _bookService.Get(id);
if (book == null)
{
return NotFound();
}
_bookService.Update(id, bookIn);
return NoContent();
}
[HttpDelete("{id:length(24)}")]
public IActionResult Delete(string id)
{
var book = _bookService.Get(id);
if (book == null)
{
return NotFound();
}
_bookService.Remove(book.Id);
return NoContent();
}
}
}
The preceding web API controller:
- Uses the
BookServiceclass to perform CRUD operations. - Contains action methods to support GET, POST, PUT, and DELETE HTTP requests.
- Calls CreatedAtRoute in the
Createaction method to return an HTTP 201 response. Status code 201 is the standard response for an HTTP POST method that creates a new resource on the server.CreatedAtRoutealso adds aLocationheader to the response. TheLocationheader specifies the URI of the newly created book.
Test the web API
- Build and run the app.
- Navigate to
http://localhost:to test the controller's parameterless/api/books Getaction method. The following JSON response is displayed:JSON[ { "id":"5bfd996f7b8e48dc15ff215d", "bookName":"Design Patterns", "price":54.93, "category":"Computers", "author":"Ralph Johnson" }, { "id":"5bfd996f7b8e48dc15ff215e", "bookName":"Clean Code", "price":43.15, "category":"Computers", "author":"Robert C. Martin" } ] - Navigate to
http://localhost:to test the controller's overloaded/api/books/{id here} Getaction method. The following JSON response is displayed:JSON{ "id":"{ID}", "bookName":"Clean Code", "price":43.15, "category":"Computers", "author":"Robert C. Martin" }
Configure JSON serialization options
There are two details to change about the JSON responses returned in the Test the web API section:
- The property names' default camel casing should be changed to match the Pascal casing of the CLR object's property names.
- The
bookNameproperty should be returned asName.
To satisfy the preceding requirements, make the following changes:
- In
Startup.ConfigureServices, chain the following highlighted code on to theAddMvcmethod call:C#public void ConfigureServices(IServiceCollection services) { services.Configure( Configuration.GetSection(nameof(BookstoreDatabaseSettings))); services.AddSingleton (sp => sp.GetRequiredService >().Value); services.AddSingleton (); services.AddMvc() .AddJsonOptions(options => options.UseMemberCasing()) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } With the preceding change, property names in the web API's serialized JSON response match their corresponding property names in the CLR object type. For example, theBookclass'sAuthorproperty serializes asAuthor. - In Models/Book.cs, annotate the
BookNameproperty with the following [JsonProperty] attribute:C#[BsonElement("Name")] [JsonProperty("Name")] public string BookName { get; set; }The[JsonProperty]attribute's value ofNamerepresents the property name in the web API's serialized JSON response. - Add the following code to the top of Models/Book.cs to resolve the
[JsonProperty]attribute reference:C#using Newtonsoft.Json; - Repeat the steps defined in the Test the web API section. Notice the difference in JSON property names.
Happy H@X0ring!
🌯🌯🌯🌯🌯🌯🌯🌯🌯