Create WebAPI
Create a WebAPI Project to consume data from Cosmos DB
Create project
Let us create an asp.net web api project inside a folder called CosmosDemo by running the following command:
dotnet new webapiCreate Item model in a folder called Models
Item model in a folder called ModelsAt the root of your project, create the Models folder and a class called Item inside it. Replace the contents of it with the code shown below:
using Newtonsoft.Json;
namespace CosmosDemo.Models;
public class Item
{
[JsonProperty(PropertyName = "id")]
public string? Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
[JsonProperty(PropertyName = "isComplete")]
public bool Completed { get; set; }
}Create a folder called Services
Services Inside the folder define an interface ICosmosDbService as given in the code below:
In the same folder create a class CosmosDbService that implements the interface as shown below:
Replace Program.cs
Program.cs Replace Program.cs class with the code shown below:
Add ItemsController
Add ItemsControllerIn the Controllers folder create a class ItemsController as shown below:
Modify appsettings.json
appsettings.jsonReplace the contents of appsettings.json file with the one shown below:
Add values for the Account and Key (which you obtained from Azure Cosmos Portal)
Remove others
You might want to remove weather controller and weather model which was created as part of the template!
Alternatively Download repo
Alternatively, you can download this project from my repository and only add the Account and Key values in appsettings.json, with your values:
Last updated