Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This tutorial creates a web API that runs 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
The latest version of Visual Studio with the ASP.NET and web development workload.
Configure MongoDB
Enable MongoDB and MongoDB Shell access from anywhere on the development machine (Windows/Linux/macOS):
Download and Install MongoDB Shell:
- macOS/Linux: Choose a directory to extract the MongoDB Shell to. Add the resulting path for
mongoshto thePATHenvironment variable. - Windows: MongoDB Shell (mongosh.exe) is installed at C:\Users\{USER NAME}\AppData\Local\Programs\mongosh. Add the resulting path for
mongosh.exeto thePATHenvironment variable.
- macOS/Linux: Choose a directory to extract the MongoDB Shell to. Add the resulting path for
Download and Install MongoDB:
- macOS/Linux: Verify the directory that MongoDB was installed at, usually in /usr/local/mongodb. Add the resulting path for
mongodbto thePATHenvironment variable. - Windows: MongoDB is installed at C:\Program Files\MongoDB by default. Add C:\Program Files\MongoDB\Server\{VERSION NUMBER}\bin to the
PATHenvironment variable.
- macOS/Linux: Verify the directory that MongoDB was installed at, usually in /usr/local/mongodb. Add the resulting path for
Choose a Data Storage Directory: Select a directory on your development machine for storing data. Create the directory if it doesn't exist. The MongoDB Shell doesn't create new directories:
- macOS/Linux: For example,
/usr/local/var/mongodb. - Windows: For example,
C:\\BooksData.
- macOS/Linux: For example,
In the OS command shell (not the MongoDB Shell), use the following command to connect to MongoDB on default port 27017. Replace
{DATA DIRECTORY PATH}with the directory chosen in the previous step.mongod --dbpath {DATA DIRECTORY PATH}
Use the previously installed MongoDB Shell in the following steps to create a database, make collections, and store documents. For more information on MongoDB Shell commands, see mongosh.
Open a MongoDB command shell instance by launching
mongosh.exe, or by running the following command in the command shell:mongoshIn the command shell connect to the default test database by running:
use BookStoreA database named BookStore is created if it doesn't already exist. If the database does exist, its connection is opened for transactions.
Create a
Bookscollection using following command:db.createCollection('Books')The following result is displayed:
{ "ok" : 1 }Define a schema for the
Bookscollection and insert two documents using the following command:db.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" }])A result similar to the following is displayed:
{ "acknowledged" : true, "insertedIds" : [ ObjectId("61a6058e6c43f32854e51f51"), ObjectId("61a6058e6c43f32854e51f52") ] }Note
The
ObjectIds shown in the preceding result won't match those shown in the command shell.View the documents in the database using the following command:
db.Books.find().pretty()A result similar to the following is displayed:
{ "_id" : ObjectId("61a6058e6c43f32854e51f51"), "Name" : "Design Patterns", "Price" : 54.93, "Category" : "Computers", "Author" : "Ralph Johnson" } { "_id" : ObjectId("61a6058e6c43f32854e51f52"), "Name" : "Clean Code", "Price" : 43.15, "Category" : "Computers", "Author" : "Robert C. Martin" }The schema adds an autogenerated
_idproperty of typeObjectIdfor each document.
Create the ASP.NET Core web API project
- Go to File > New > Project.
- Select the ASP.NET Core Web API project type, and select Next.
- Name the project BookStoreApi, and select Next.
- In the Additional information dialog:
- Confirm the Framework is .NET 10.0 (Long Term Support).
- Confirm the checkbox for Use controllers is unchecked.
- Confirm the checkbox for Enable OpenAPI support is checked.
- Select Create.
In the Package Manager Console window, navigate to the project root. Run the following command to install the .NET driver for MongoDB:
Install-Package MongoDB.Driver
Add an entity model
Add a Models directory to the project root.
Add a
Bookclass to the Models directory with the following code:using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace BookStoreApi.Models; public class Book { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string? Id { get; set; } [BsonElement("Name")] public string BookName { get; set; } = null!; public decimal Price { get; set; } public string Category { get; set; } = null!; public string Author { get; set; } = null!; }In the preceding class, the
Idproperty is:- Required for mapping the Common Language Runtime (CLR) object to the MongoDB collection.
- Annotated with
[BsonId]to make this property the document's primary key. - Annotated with
[BsonRepresentation(BsonType.ObjectId)]to allow passing the parameter as typestringinstead of an ObjectId structure. Mongo handles the conversion fromstringtoObjectId.
The
BookNameproperty 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:{ "BookStoreDatabase": { "ConnectionString": "mongodb://localhost:27017", "DatabaseName": "BookStore", "BooksCollectionName": "Books" }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }Add a
BookStoreDatabaseSettingsclass to the Models directory with the following code:namespace BookStoreApi.Models; public class BookStoreDatabaseSettings { public string ConnectionString { get; set; } = null!; public string DatabaseName { get; set; } = null!; public string BooksCollectionName { get; set; } = null!; }The preceding
BookStoreDatabaseSettingsclass is used to store theappsettings.jsonfile'sBookStoreDatabaseproperty values. The JSON and C# property names are named identically to ease the mapping process.Add the following highlighted code to
Program.cs:var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.Configure<BookStoreDatabaseSettings>( builder.Configuration.GetSection("BookStoreDatabase"));In the preceding code, the configuration instance to which the
appsettings.jsonfile'sBookStoreDatabasesection binds is registered in the Dependency Injection (DI) container. For example, theBookStoreDatabaseSettingsobject'sConnectionStringproperty is populated with theBookStoreDatabase:ConnectionStringproperty inappsettings.json.Add the following code to the top of
Program.csto resolve theBookStoreDatabaseSettingsreference:using BookStoreApi.Models;
Add a CRUD operations service
Add a Services directory to the project root.
Add a
BooksServiceclass to the Services directory with the following code:using BookStoreApi.Models; using Microsoft.Extensions.Options; using MongoDB.Driver; namespace BookStoreApi.Services; public class BooksService(IOptions<BookStoreDatabaseSettings> bookStoreDatabaseSettings) { private readonly IMongoCollection<Book> _booksCollection = new MongoClient(bookStoreDatabaseSettings.Value.ConnectionString) .GetDatabase(bookStoreDatabaseSettings.Value.DatabaseName) .GetCollection<Book>(bookStoreDatabaseSettings.Value.BooksCollectionName); public async Task<List<Book>> GetAsync() => await _booksCollection.Find(_ => true).ToListAsync(); public async Task<Book?> GetAsync(string id) => await _booksCollection.Find(x => x.Id == id).FirstOrDefaultAsync(); public async Task CreateAsync(Book newBook) => await _booksCollection.InsertOneAsync(newBook); public async Task UpdateAsync(string id, Book updatedBook) => await _booksCollection.ReplaceOneAsync(x => x.Id == id, updatedBook); public async Task RemoveAsync(string id) => await _booksCollection.DeleteOneAsync(x => x.Id == id); }In the preceding code, a
BookStoreDatabaseSettingsinstance is retrieved from DI via constructor injection. This technique provides access to theappsettings.jsonconfiguration values that were added in the Add a configuration model section.Add the following highlighted code to
Program.cs:var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.Configure<BookStoreDatabaseSettings>( builder.Configuration.GetSection("BookStoreDatabase")); builder.Services.AddSingleton<BooksService>();In the preceding code, the
BooksServiceclass is registered with DI to support constructor injection in consuming classes. The singleton service lifetime is most appropriate becauseBooksServicetakes 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
Program.csto resolve theBooksServicereference:using BookStoreApi.Services;
The BooksService class uses the following MongoDB.Driver members to run CRUD operations against the database:
MongoClient: Reads the server instance for running database operations. The constructor of this class is provided in the MongoDB connection string:
public class BooksService(IOptions<BookStoreDatabaseSettings> bookStoreDatabaseSettings) { private readonly IMongoCollection<Book> _booksCollection = new MongoClient(bookStoreDatabaseSettings.Value.ConnectionString) .GetDatabase(bookStoreDatabaseSettings.Value.DatabaseName) .GetCollection<Book>(bookStoreDatabaseSettings.Value.BooksCollectionName);IMongoDatabase: Represents the Mongo database for running operations. This tutorial uses the generic GetCollection<TDocument>(collection) method on the interface to gain access to data in a specific collection. Run CRUD operations against the collection after this method is called. In the
GetCollection<TDocument>(collection)method call:collectionrepresents the collection name.TDocumentrepresents the CLR object type stored in the collection.
GetCollection<TDocument>(collection) returns a MongoCollection object representing the collection. In this tutorial, the following methods are invoked on the collection:
- DeleteOneAsync: Deletes a single document matching the provided search criteria.
- Find<TDocument>: Returns all documents in the collection matching the provided search criteria.
- InsertOneAsync: Inserts the provided object as a new document in the collection.
- ReplaceOneAsync: Replaces the single document matching the provided search criteria with the provided object.
Create endpoints
In the Program.cs file, replace the weatherforecast example with the following books endpoints:
var booksGroup = app.MapGroup("/books");
booksGroup.MapGet("/", async (BooksService booksService) =>
{
var books = await booksService.GetAsync();
return Results.Ok(books);
});
booksGroup.MapGet("/{id:length(24)}", async (string id, BooksService booksService) =>
{
var book = await booksService.GetAsync(id);
return book is null ? Results.NotFound() : Results.Ok(book);
});
booksGroup.MapPost("/", async (Book newBook, BooksService booksService) =>
{
await booksService.CreateAsync(newBook);
return Results.Created($"/books/{newBook.Id}", newBook);
});
booksGroup.MapPut("/{id:length(24)}", async (string id, Book updatedBook, BooksService booksService) =>
{
var book = await booksService.GetAsync(id);
if (book is null)
{
return Results.NotFound();
}
updatedBook.Id = book.Id;
await booksService.UpdateAsync(id, updatedBook);
return Results.NoContent();
});
booksGroup.MapDelete("/{id:length(24)}", async (string id, BooksService booksService) =>
{
var book = await booksService.GetAsync(id);
if (book is null)
{
return Results.NotFound();
}
await booksService.RemoveAsync(id);
return Results.NoContent();
});
The preceding code:
- Uses MapGroup to help organize all the books related endpoints, and provides a common route prefix of
/booksfor all the endpoints within the group. - Contains endpoints to support GET, POST, PUT, and DELETE HTTP requests.
- Uses the
BooksServiceclass to run CRUD operations. - Calls Created 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.Createdalso adds aLocationheader to the response. TheLocationheader specifies the URI of the newly created book.
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
Program.cs, add the following highlighted code:var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.Configure<BookStoreDatabaseSettings>( builder.Configuration.GetSection("BookStoreDatabase")); builder.Services.AddSingleton<BooksService>(); builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options => { options.SerializerOptions.PropertyNamingPolicy = null; });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, the
Bookclass'sAuthorproperty serializes asAuthorinstead ofauthor.In
Models/Book.cs, annotate theBookNameproperty with the[JsonPropertyName]attribute:[BsonElement("Name")] [JsonPropertyName("Name")] public string BookName { get; set; } = null!;The
[JsonPropertyName]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.csto resolve the[JsonPropertyName]attribute reference:using System.Text.Json.Serialization;Repeat the steps defined in the Test the web API section. Notice the difference in JSON property names.
Test the web API
This tutorial uses Endpoints Explorer and .http files to test the API.
Build and run the app.
In Endpoints Explorer, right-click the first GET endpoint
/books, and select Generate request.The following content is added to the
BookStoreApi.httpfile. If this is the first time that a request is generated, the file is created in the project root.@BookStoreApi_HostAddress = https://localhost:{PORT} GET {{BookStoreApi_HostAddress}}/books ###The port number should already be set to the port used by the app, for example,
https://localhost:56874. If that's not the case you can find your port number in the output window when you launch the app.Select the Send request link above the new
GETrequest line.The GET request is sent to the app and the response is displayed in the Response pane.
The response body shows the JSON result containing the book entries similar to the following:
[ { "Id": "61a6058e6c43f32854e51f51", "Name": "Design Patterns", "Price": 54.93, "Category": "Computers", "Author": "Ralph Johnson" }, { "Id": "61a6058e6c43f32854e51f52", "Name": "Clean Code", "Price": 43.15, "Category": "Computers", "Author": "Robert C. Martin" } ]To retrieve a single book, right-click the
/books/{id}, params (string id)GET endpoint in the Endpoints Explorer, and select Generate request.The following content is appended to the
BookStoreApi.httpfile:@id=string GET {{BookStoreApi_HostAddress}}/books/{{id}} ###Replace
idvariable with one of the IDs returned from the earlier request, for example:@id="61a6058e6c43f32854e51f52" GET {{BookStoreApi_HostAddress}}/books/{{id}} ###Select the Send request link above the new
GETrequest line.The GET request is sent to the app and the response is displayed in the Response pane.
The response body shows JSON similar to the following:
{ "Id": "61a6058e6c43f32854e51f52", "Name": "Clean Code", "Price": 43.15, "Category": "Computers", "Author": "Robert C. Martin" }To test the POST endpoint, right-click the
/booksPOST endpoint and select Generate request.The following content is added to the
BookStoreApi.httpfile:POST {{BookStoreApi_HostAddress}}/books Content-Type: application/json { //Book } ###Replace the Book comment with a book object as the JSON request body:
POST {{BookStoreApi_HostAddress}}/books Content-Type: application/json { "Name": "The Pragmatic Programmer", "Price": 49.99, "Category": "Computers", "Author": "Andy Hunt" } ###Select the Send request link above the
POSTrequest line.The POST request is sent to the app, and the response is displayed in the Response pane. The response should include the newly created book with its assigned ID.
Lastly, to delete a book, right-click the
/books/{id}, params (string id)DELETE endpoint and select Generate request.The following content is appended to the
BookStoreApi.httpfile:DELETE {{BookStoreApi_HostAddress}}/books/{{id}} ###Replace the
idvariable with one of the IDs returned from the earlier request, and click Send request. For example:DELETE {{BookStoreApi_HostAddress}}/books/67f417517ce1b36aeab71236 ###
Add authentication support to a web API
ASP.NET Core Identity adds user interface (UI) login functionality to ASP.NET Core web apps. To secure web APIs and SPAs, use one of the following:
Duende Identity Server is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core. Duende Identity Server enables the following security features:
- Authentication as a Service (AaaS)
- Single sign-on/off (SSO) over multiple application types
- Access control for APIs
- Federation Gateway
Important
Duende Software might require you to pay a license fee for production use of Duende Identity Server.
For more information, see the Duende Identity Server documentation (Duende Software website).
Related content
ASP.NET Core