Kailash's Blogs

Using MongoDB with ASP.NET Core Web API

Kailash Chandra Behera | Wednesday, July 24, 2024
Kailash's Blogs
Introduction

MongoDB database nowadays is becoming more popular. Here this blog post creates a ASP.NET Core web API with MongoDB that runs Create, Read, Update, and Delete (CRUD) operations on a MongoDB NoSQL database.

Getting Started

In my previous blog post, I explained how to download and install MongoDB. There I explained each step for MongoDB installation in detail including set up MongoDB database to access from anywhere on the development machine

Visit my blog post to learn about installation of MongoDB. The following activities we are going to perform:

  • Create ASP.NET Core web API.
  • Add MongoDB model.
  • Configure MongoDB model.
  • Add MongoDB Service Class.
  • Perform MongoDB CRUD operations.
  • Customize JSON serialization.

Create ASP.NET Core Web API

  • Go to File > New > Project.
  • Select the ASP.NET Core Web API project type and select Next.
  • Name the project ManageSchoolAPI and select Next.
  • Select the .NET 8.0 (Long Term support) framework and select Create.
  • Click on the link to know how to install MongoDB driver.

Create MongoDB Model.

We will create a model to store and retrieve data from back-end data stores. Follow the steps to create a model in ASP.NET Core Web API.

  1. Add a directory with the name Models to the project root.
  2. Add a StudentMaster class to the Models directory with the following code:
     using MongoDB.Bson;  
     using MongoDB.Bson.Serialization.Attributes;  
     namespace ManageSchoolAPI.Models;  
     public class StudentMaster  
     {  
       [BsonId]  
       [BsonRepresentation(BsonType.ObjectId)]  
       public string? ID { get; set; }  
       [BsonElement("Name")]  
       public string StudentName { get; set; } = null!;  
       public string RollNumber { get; set; }  
       public string Division { get; set; } = null!;  
       public string Standard { get; set; } = null!;  
     }  
    
  3. In the preceding class, ID is required to map the Common Language Runtime (CLR) object to the MongoDB collection and the attributes are:

    • BsonId to make this property the document's primary key.
    • Annotated with BsonRepresentation(BsonType.ObjectId) to allow passing the parameter as type string instead of an ObjectId structure. Mongo handles the conversion from string to ObjectId.

  4. The StudentName property is annotated with the BsonElement attribute. The attribute's value of Name represents the property name in the MongoDB collection

Configure MongoDB Model

  • Add the following database configuration values to appsettings.json:
     {  
       "SchoolDatabase": {  
         "ConnectionString": "mongodb://localhost:27017",  
         "DatabaseName": "SchoolManagement",  
         "StudentCollectionName": "StudentMaster"  
       },  
       "Logging": {  
         "LogLevel": {  
           "Default": "Information",  
           "Microsoft.AspNetCore": "Warning"  
         }  
       },  
       "AllowedHosts": "*"  
     }  
    
  • Add a SchoolDatabaseSettings class to the Models directory with the following code, the class is used to store the appsettings.json file's SchoolDatabase property values. The JSON and C# property names are named identically to ease the mapping process.

     namespace ManageSchoolAPI.Models;  
     public class SchoolDatabaseSettings  
     {  
       public string ConnectionString { get; set; } = null!;  
       public string DatabaseName { get; set; } = null!;  
       public string StudentCollectionName { get; set; } = null!;  
     }  
    
  • The following code is the configuration instance to which the appsettings.json file's SchoolDatabase section binds is registered in the Dependency Injection (DI) container. For example, the SchoolDatabaseSettings object's ConnectionString property is populated with the SchoolDatabase:ConnectionString property in appsettings.json. add this code in the program.cs file after instance of web application and take reference of Models namespace.

     var builder = WebApplication.CreateBuilder(args);  
     // Add services to the container.  
       builder.Services.Configure<SchoolDatabaseSettings>(  
       builder.Configuration.GetSection("SchoolDatabase"));  
    

Add MongoDB Service Class

  • Add a Services directory to the project root.
  • Add a MongoDB Service class to the Services directory with the following code:
     using ManageSchoolAPI.Models;  
     using Microsoft.Extensions.Options;  
     using MongoDB.Driver;  
     namespace ManageSchoolAPI.Services;  
     public class MongoDBService  
     {  
       private readonly IMongoCollection<StudentMaster> _studentCollection;  
       public MongoDBService(  
         IOptions<SchoolDatabaseSettings> schoolDatabaseSettings)  
       {  
         var mongoClient = new MongoClient(  
           schoolDatabaseSettings.Value.ConnectionString);  
         var mongoDatabase = mongoClient.GetDatabase(  
           schoolDatabaseSettings.Value.DatabaseName);  
         _booksCollection = mongoDatabase.GetCollection<StudentMaster>(  
           schoolDatabaseSettings.Value.StudentCollectionName);  
       }  
       public async Task<List<StudentMaster>> GetAsync() =>  
         await _studentCollection.Find(_ => true).ToListAsync();  
       public async Task<StudentMaster?> GetAsync(string id) =>  
         await _studentCollection.Find(x => x.Id == id).FirstOrDefaultAsync();  
       public async Task CreateAsync(StudentMaster newStudent) =>  
         await _studentCollection.InsertOneAsync(newStudent);  
       public async Task UpdateAsync(string id, StudentMaster updatedStudent) =>  
         await _studentCollection.ReplaceOneAsync(x => x.Id == id, updatedStudent);  
       public async Task RemoveAsync(string id) =>  
         await _studentCollection.DeleteOneAsync(x => x.Id == id);  
     }  
    
  • Register the MongoDB Service by adding following code in program.cs file, use the Services namespace after adding the code.
     var builder = WebApplication.CreateBuilder(args);  
     // Add services to the container.  
     builder.Services.Configure<StudentDatabaseSettings>(  
       builder.Configuration.GetSection("StudentDatabase"));  
     builder.Services.AddSingleton<MongoDBService>();  
    

Add a Controller

Add a class to the Controllers directory with the following code and name the class StudentController:

 using MongoSchoolAPI.Models;  
 using MongoSchoolAPI.Services;  
 using Microsoft.AspNetCore.Mvc;  
 namespace ManageSchoolAPI.Controllers;  
 [ApiController]  
 [Route("api/[controller]")]  
 public class StudentController : ControllerBase  
 {  
   private readonly MongoDBService _mongodbService;  
   public StudentController(MongoDBService mongodbService) =>  
     _mongodbService = mongodbService;  
   [HttpGet]  
   public async Task<List<StudentMaster>> Get() =>  
     await _mongodbService.GetAsync();  
   [HttpGet("{id:length(24)}")]  
   public async Task<ActionResult<StudentMaster>> Get(string id)  
   {  
     var student = await _mongodbService.GetAsync(id);  
     if (student is null)  
     {  
       return NotFound();  
     }  
     return student;  
   }  
   [HttpPost]  
   public async Task<IActionResult> Post(StudentMaster newStudent)  
   {  
     await _mongodbService.CreateAsync(newStudent);  
     return CreatedAtAction(nameof(Get), new { id = newStudent.Id }, newStudent);  
   }  
   [HttpPut("{id:length(24)}")]  
   public async Task<IActionResult> Update(string id, StudentMaster updatedStudent)  
   {  
     var student = await _mongodbService.GetAsync(id);  
     if (student is null)  
     {  
       return NotFound();  
     }  
     updatedStudent.Id = student.Id;  
     await _mongodbService.UpdateAsync(id, updatedStudent);  
     return NoContent();  
   }  
   [HttpDelete("{id:length(24)}")]  
   public async Task<IActionResult> Delete(string id)  
   {  
     var student = await _mongodbService.GetAsync(id);  
     if (student is null)  
     {  
       return NotFound();  
     }  
     await _mongodbService.RemoveAsync(id);  
     return NoContent();  
   }  
 }  

In the preceding controller class, MongoDB service class is used to run CRUD operations. it has four action methods to support GET, POST, PUT, and DELETE HTTP requests.

Calls CreatedAtAction in the Create action 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. CreatedAtAction also adds a Location header to the response. The Location header specifies the URI of the newly created Student.

Test Web API MongoDB

Build and run the app. The app will run with Swagger as the Swagger by default is enabled. Execute the GET, POST, PUT, and DELETE HTTP requests by providing the appropriate request parameter.

Summary

In the above of this blog post, we learned how to create web api with Mongodb. We discussed each steps to use MongoDB with ASP.NET Core Web API. I hope this post is helpful to you.

Thanks