Introduction
Creating a complete ASP.NET Core Web API for CRUD operations with a Cosmos Database is a multi-step process. In this tutorial, we'll create a sample application called "CSharpCornerArticles" to manage articles. We'll cover all the necessary steps, including setting up the Cosmos DB, creating the Web API, and implementing CRUD operations.
Prerequisites
- Visual Studio 2019 or later
- .NET SDK 3.1 or later
- Azure Cosmos DB Account
Step 1. Create a Cosmos DB Account
- Go to the Azure Portal.
- Click on "+ Create a resource" and search for "Azure Cosmos DB."
- Fill in the required information like Subscription, Resource Group, and Database Account Name.
- Choose "SQL (Core)" as the API and leave the rest as default.
- Click "Review + Create" and then "Create" to create the Cosmos DB account.
Step 2. Create an ASP.NET Core Web API Project
- Open Visual Studio and select "Create a new project."
- Choose "ASP.NET Core Web Application" and click "Next."
- Enter a project name, choose a location, and click "Create."
- In the "Create a new ASP.NET Core web application" dialog, select the "API" template and click "Create."
Step 3. Add Required NuGet Packages
In the CSharpCornerArticles.csproj file, add the following NuGet packages.
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.23.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.CosmosDB" Version="3.0.10" />
</ItemGroup>
Save the file, and Visual Studio should automatically restore the packages.
Step 4. Configure Cosmos DB Connection
In the appsettings.json file, add your Cosmos DB connection string.
{
"ConnectionStrings": {
"CosmosDB": "YOUR_COSMOS_DB_CONNECTION_STRING"
},
"Logging": {
// ...
}
}
Step 5. Create a Model
Create a model for the articles. Right-click on the Models folder and add a new class named "Article.cs".
using Newtonsoft.Json;
public class Article
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
}
Step 6. Create a Repository
Create a repository to interact with Cosmos DB. Add a new class named "ArticleRepository.cs" to the project.
using Microsoft.Azure.Cosmos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class ArticleRepository
{
private readonly Container _container;
public ArticleRepository(CosmosClient cosmosClient, string databaseName, string containerName)
{
_container = cosmosClient.GetContainer(databaseName, containerName);
}
public async Task<IEnumerable<Article>> GetArticlesAsync()
{
var query = _container.GetItemQueryIterator<Article>(new QueryDefinition("SELECT * FROM c"));
var results = new List<Article>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
public async Task<Article> GetArticleAsync(string id)
{
try
{
var response = await _container.ReadItemAsync<Article>(id, new PartitionKey(id));
return response.Resource;
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
}
public async Task<Article> CreateArticleAsync(Article article)
{
var response = await _container.CreateItemAsync(article, new PartitionKey(article.Id));
return response.Resource;
}
public async Task<Article> UpdateArticleAsync(string id, Article article)
{
var response = await _container.UpsertItemAsync(article, new PartitionKey(id));
return response.Resource;
}
public async Task DeleteArticleAsync(string id)
{
await _container.DeleteItemAsync<Article>(id, new PartitionKey(id));
}
}
Step 7. Create a Controller for CRUD Operations
Add a new controller named "ArticlesController.cs" to the Controllers folder.
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
[Route("api/[controller]")]
[ApiController]
public class ArticlesController : ControllerBase
{
private readonly ArticleRepository _repository;
public ArticlesController(ArticleRepository repository)
{
_repository = repository;
}
[HttpGet]
public async Task<IEnumerable<Article>> Get()
{
return await _repository.GetArticlesAsync();
}
[HttpGet("{id}")]
public async Task<ActionResult<Article>> Get(string id)
{
var article = await _repository.GetArticleAsync(id);
if (article == null)
return NotFound();
return article;
}
[HttpPost]
public async Task<ActionResult<Article>> Post([FromBody] Article article)
{
var createdArticle = await _repository.CreateArticleAsync(article);
return CreatedAtAction(nameof(Get), new { id = createdArticle.Id }, createdArticle);
}
[HttpPut("{id}")]
public async Task<ActionResult<Article>> Put(string id, [FromBody] Article article)
{
var updatedArticle = await _repository.UpdateArticleAsync(id, article);
if (updatedArticle == null)
return NotFound();
return updatedArticle;
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
await _repository.DeleteArticleAsync(id);
return NoContent();
}
}
Step 8. Configure Dependency Injection
In the Startup.cs file, add the following code to configure dependency injection for the repository.
services.AddSingleton((provider) =>
{
var cosmosClient = new CosmosClient(Configuration.GetConnectionString("CosmosDB"));
return new ArticleRepository(cosmosClient, "YOUR_DATABASE_NAME", "YOUR_CONTAINER_NAME");
});
Step 9. Run the Application
Build and run the application. You can use tools like Postman or Swagger to test your CRUD operations.
ASP.NET Core Web API for CRUD operations with a Cosmos Database. This application allows you to manage articles with real-world use cases. Make sure to replace "YOUR_COSMOS_DB_CONNECTION_STRING," "YOUR_DATABASE_NAME," and "YOUR_CONTAINER_NAME" with your Cosmos DB details.