Create a Web API with ASP.NET Core 7 and MongoDB
Tags: webdev, csharp, tutorial, beginners
Published: 2023-03-22 11:36:58

In this tutorial, we will learn how to create a Web API using ASP.NET Core 7 and MongoDB. ASP.NET Core is a cross-platform, high-performance framework for building modern, cloud-based, Internet-connected applications. MongoDB is a popular NoSQL database that stores data in JSON-like documents, which makes it perfect for working with Web APIs.

We will create a simple CRUD (Create, Read, Update, Delete) API for managing a list of products. By the end of this tutorial, you'll have a fully functional Web API that you can use as a starting point for your own projects.

## Prerequisites:

1. Rider, Visual Studio or Visual Studio Code with .NET 7 or higher.
2. MongoDB installed or MongoDB Atlas account (cloud-based MongoDB service).
3. Basic knowledge of C# and ASP.NET Core.

## Steps:

- **Create a new ASP.NET Core Web API project:**

Open Visual Studio and create a new project. Select "ASP.NET Core Web Application" and name it "ProductsAPI". On the next screen, choose the "API" template and make sure you have .NET 7 selected as the target framework.

- **Install the MongoDB driver:**

To interact with MongoDB, we need to install the MongoDB .NET driver. Open the terminal and navigate to your project folder. Run the following command to install the package:

```
dotnet add package MongoDB.Driver
```

- **Configure MongoDB connection:**

Open the "appsettings.json" file and add a "MongoDBSettings" section with the "ConnectionString" and "DatabaseName" properties:

```json
{
  "MongoDBSettings": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "ProductsDB"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
```

- **Create MongoDB settings model:**

Create a new folder called "Models" in your project, and inside it, create a new class named "MongoDBSettings.cs". Define the properties for the MongoDB connection settings:

```csharp
public class MongoDBSettings
{
    public string ConnectionString { get; set; }
    public string DatabaseName { get; set; }
}
```

- **Set up MongoDB context:**

Create a new folder called "Data" in your project, and inside it, create a new class named "MongoDBContext.cs". This class will handle the database connection and provide access to the collections:

```csharp
public class MongoDBContext
{
    private readonly IMongoDatabase _database;

    public MongoDBContext(string connectionString, string databaseName)
    {
        var client = new MongoClient(connectionString);
        _database = client.GetDatabase(databaseName);
    }

    public IMongoCollection<Product> Products => _database.GetCollection<Product>("Products");
}
```

- **Create the Product model:**

Inside the "Models" folder, create a Product model class named "Product.cs". Define the properties for the product:

```csharp
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class Product
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonElement("Name")]
    public string Name { get; set; }

    [BsonElement("Category")]
    public string Category { get; set; }

    [BsonElement("Price")]
    public decimal Price { get; set; }
}
```

- **Update the Program.cs file:**

Replace the content of the Program.cs file with the following code:

```csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using ProductsAPI.Models;
using ProductsAPI.Data;
using MongoDB.Driver;

var builder = WebApplication.CreateBuilder(args);

// Register services here
builder.Services.Configure<MongoDBSettings>(builder.Configuration.GetSection(nameof(MongoDBSettings)));

builder.Services.AddSingleton<MongoDBContext>(serviceProvider =>
{
    var settings = serviceProvider.GetRequiredService<IOptions<MongoDBSettings>>().Value;
    return new MongoDBContext(settings.ConnectionString, settings.DatabaseName);
});

// Add controllers
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

```

- **Create the ProductsController:**

Create a new folder called "Controllers" in your project, and inside it, create a new class named "ProductsController.cs". Implement the CRUD operations for the Product model:

```csharp
using Microsoft.AspNetCore.Mvc;
using ProductsAPI.Data;
using ProductsAPI.Models;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly MongoDBContext _context;

    public ProductsController(MongoDBContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<IEnumerable<Product>> Get()
    {
        return await _context.Products.Find(_ => true).ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<Product>> Get(string id)
    {
        var product = await _context.Products.Find(p => p.Id == id).FirstOrDefaultAsync();

        if (product == null)
        {
            return NotFound();
        }

        return product;
    }

    [HttpPost]
    public async Task<ActionResult<Product>> Create(Product product)
    {
        await _context.Products.InsertOneAsync(product);
        return CreatedAtRoute(new { id = product.Id }, product);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(string id, Product productIn)
    {
        var product = await _context.Products.Find(p => p.Id == id).FirstOrDefaultAsync();

        if (product == null)
        {
            return NotFound();
        }

        await _context.Products.ReplaceOneAsync(p => p.Id == id, productIn);

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string id)
    {
        var product = await _context.Products.Find(p => p.Id == id).FirstOrDefaultAsync();

    if (product == null)
    {
        return NotFound();
    }

    await _context.Products.DeleteOneAsync(p => p.Id == id);

    return NoContent();
}

```

Now you have a fully functional Web API with ASP.NET Core 7 and MongoDB. You can test the API using tools like Postman or Swagger. To add Swagger support, follow these steps:


- **Add Swagger support:**

Install the required NuGet packages:

```
dotnet add package Swashbuckle.AspNetCore
```

Add the following code in the Program.cs file, under the `builder.Services.AddControllers();` line:


```csharp
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "ProductsAPI", Version = "v1" });
});
```

Add the Swagger middleware in the Program.cs file, after the app.UseRouting(); line:

```
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ProductsAPI v1"));

```

- **Test the API:**

Run the application and navigate to the Swagger UI by visiting https://localhost:<port>/swagger in your browser. You should see the API documentation and be able to test the endpoints directly from the Swagger UI.