Creating a complete CRUD (Create, Read, Update, Delete) API using ASP.NET Core with a MongoDB database is a common task in web development. In this article, we'll walk through each step to build a real-world API for managing articles. We'll use a model called CSharpCornerArticles to represent articles.
Prerequisites
Before we begin, make sure you have the following tools and dependencies installed.
- .NET Core SDK
- Visual Studio Code or another code editor of your choice.
- MongoDB is installed and running locally.
Step 1. Create a New ASP.NET Core Web API Project
Open your terminal or command prompt and run the following commands to create a new ASP.NET Core Web API project.
dotnet new webapi -n CSharpCornerArticlesAPI
cd CSharpCornerArticlesAPI
This will create a new web API project named CSharpCornerArticlesAPI.
Step 2. Install Required Packages
We need to install the MongoDB driver for .NET to interact with the database. Run the following command in the project directory.
dotnet add package MongoDB.Driver
This will install the MongoDB driver. NET.
Step 3. Define the Model
In the project, create a folder named Models, and inside that folder, create a class file named CSharpCornerArticle.cs. This class will represent our article model.
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
Author: Sardar Mudassar Ali Khan
public class CSharpCornerArticle
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
We use the BsonId and BsonRepresentation attributes to specify that the Id property is the primary key and should be represented as an ObjectId in the MongoDB database.
Step 4. Create a MongoDB Configuration
In the project, create a folder named Configuration, and inside that folder, create a class file named MongoDbConfiguration.cs to configure the MongoDB connection.
Author: Sardar Mudassar Ali Khan
public class MongoDbConfiguration
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
Step 5. Configure MongoDB Connection
In the appsettings.json file, add your MongoDB connection string and database name.
{
"MongoDbConfiguration": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "CSharpCornerArticlesDB"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Step 6. Create a MongoDB Context
In the project, create a folder named Data, and inside that folder, create a class file named MongoDbContext.cs to create a MongoDB context.
using MongoDB.Driver;
Author: Sardar Mudassar Ali Khan
public class MongoDbContext
{
private readonly IMongoDatabase _database;
public MongoDbContext(IOptions<MongoDbConfiguration> settings)
{
var client = new MongoClient(settings.Value.ConnectionString);
_database = client.GetDatabase(settings.Value.DatabaseName);
}
public IMongoCollection<CSharpCornerArticle> CSharpCornerArticles =>
_database.GetCollection<CSharpCornerArticle>("CSharpCornerArticles");
}
This class sets up a connection to the MongoDB database and provides access to the CSharpCornerArticles collection.
Step 7. Implement CRUD Operations
Create a folder named Controllers, and inside that folder, create a controller named CSharpCornerArticlesController.cs. This controller will handle CRUD operations for our articles.
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
Author: Sardar Mudassar Ali Khan
[Route("api/[controller]")]
[ApiController]
public class CSharpCornerArticlesController : ControllerBase
{
private readonly MongoDbContext _context;
public CSharpCornerArticlesController(IOptions<MongoDbConfiguration> settings)
{
_context = new MongoDbContext(settings);
}
[HttpGet]
public async Task<ActionResult<IEnumerable<CSharpCornerArticle>>> Get()
{
var articles = await _context.CSharpCornerArticles.Find(_ => true).ToListAsync();
return Ok(articles);
}
[HttpGet("{id}")]
public async Task<ActionResult<CSharpCornerArticle>> Get(string id)
{
var article = await _context.CSharpCornerArticles.Find(a => a.Id == id).FirstOrDefaultAsync();
if (article == null)
{
return NotFound();
}
return Ok(article);
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] CSharpCornerArticle article)
{
await _context.CSharpCornerArticles.InsertOneAsync(article);
return CreatedAtAction("Get", new { id = article.Id }, article);
}
[HttpPut("{id}")]
public async Task<IActionResult> Put(string id, [FromBody] CSharpCornerArticle article)
{
var existingArticle = await _context.CSharpCornerArticles.Find(a => a.Id == id).FirstOrDefaultAsync();
if (existingArticle == null)
{
return NotFound();
}
article.Id = existingArticle.Id;
await _context.CSharpCornerArticles.ReplaceOneAsync(a => a.Id == id, article);
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
var article = await _context.CSharpCornerArticles.Find(a => a.Id == id).FirstOrDefaultAsync();
if (article == null)
{
return NotFound();
}
await _context.CSharpCornerArticles.DeleteOneAsync(a => a.Id == id);
return NoContent();
}
}
This controller provides endpoints for listing all articles, retrieving a single article by ID, creating a new article, updating an existing article, and deleting an article.
Step 8. Test the API
You can now build and run the API by executing the following command in the project directory.
dotnet run
The API will be accessible at https://localhost:5001/api/CSharpCornerArticles
. You can use tools like Postman or Curl to test the endpoints.
Conclusion
In this article, we've built a complete CRUD API using ASP.NET Core and MongoDB. You've learned how to define a model, set up a MongoDB database, create a MongoDB context, and implement CRUD operations in a controller. This API can serve as a foundation for building more complex applications with MongoDB as the database backend.