.NET WebAPI calling Mongo DB

 This is basic WebAPI project created using .NET 7.0 version and it makes call to MongoDB database collection sitting in Mongo Cloud. The DB configuration is in appsettings.json file.


Below is the project structure - simple is the best :)


You can create simple WebApI project using VS Studio 2022 on .NET 7.0 and then replace the code of individual pages from below. Please create the folders i.e. Models, Controller, and Services as shows in above picture 

Please make sure to update DB configuration in appsettings.json according to your setup. The other important thing is to install MongoDB Driver, Core etc from Nuget Package.


Page: AppSettings.json

{

  "MovieStoreDatabase": {

    "ConnectionString": "mongodb+srv://m001-stu01-monb-basics@box.hongodb.net/test",

    "DatabaseName": "video",

    "DBCollectionName": "movieDetails"

  },

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft.AspNetCore": "Warning"

    }

  },

  "AllowedHosts": "*"


Page: Under Models, create a page name Movie.cs and paste the below code


using MongoDB.Bson;

using MongoDB.Bson.Serialization.Attributes;


namespace MVCCoreApiMovie.Models

{

    [BsonIgnoreExtraElements]

    public class Movie

    {

        [BsonId]

        [BsonRepresentation(BsonType.ObjectId)]

        public string? Id { get; set; }


        [BsonElement("title")]

        public string Title { get; set; } = null!;


        [BsonElement("year")]

        public int Year { get; set; }


        [BsonElement("rated")]

        public string Rated { get; set; } = null!;


       [BsonElement("director")]

        public string Director { get; set; } = null!;


    }

}


Page: Under Models, create a page name MovieDBSettings.cs and paste the below code

namespace MVCCoreApiMovie.Models
{
    public class MovieDBSettings
    {
        public string ConnectionString { get; set; } = null!;

        public string DatabaseName { get; set; } = null!;

        public string DBCollectionName { get; set; } = null!;
    }
}


Page: Under Controllers, create a page name MoviesController.cs and paste the below code

using MVCCoreApiMovie.Models;
using MVCCoreApiMovie.Services;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace MVCCoreApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MoviesController : ControllerBase
    {
        private readonly MovieService _movieService;

        public MoviesController(MovieService movieService) =>
            _movieService = movieService;


        // GET: api/<MoviesController>
        [HttpGet]
        public async Task<List<Movie>> Get() =>
            await _movieService.GetAsync();

        // GET api/<MoviesController>/5
        [HttpGet("{_id}")]
        public async Task<ActionResult<Movie>> Get(string movieId)
        {
            var movie = await _movieService.GetAsync(movieId);

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

            return movie;
        }

        // POST api/<MoviesController>
        [HttpPost]
        public async Task<IActionResult> Post(Movie newmovie)
        {
            await _movieService.CreateAsync(newmovie);

            return CreatedAtAction(nameof(Get), new { id = newmovie.Id, title = newmovie.Title, year = newmovie.Year},
            newmovie);
        }

        // PUT api/<MoviesController>/5
        [HttpPut("{_id}")]
        public async Task<IActionResult> Update(string id, Movie updatedmovie)
        {
            var movie = await _movieService.GetAsync(id);

            if (movie is null)
            {
                return NotFound();
            }

            updatedmovie.Id = movie.Id;

            await _movieService.UpdateAsync(id, updatedmovie);

            return NoContent();
        }

        // DELETE api/<MoviesController>/5
        [HttpDelete("{_id}")]
        public async Task<IActionResult> Delete(string id)
        {
            var movie = await _movieService.GetAsync(id);

            if (movie is null)
            {
                return NotFound();
            }

            await _movieService.RemoveAsync(id);

            return NoContent();
        }
    }
}


Page: Under Services, create a page name MovieService.cs and paste the below code

using MVCCoreApiMovie.Models;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using MongoDB.Driver.Linq;


namespace MVCCoreApiMovie.Services
{
    public class MovieService
    {
        
        private readonly IMongoCollection<Movie> _movieCollection;

        public MovieService(IOptions<MovieDBSettings> MovieDBSettings)
        {
            var mongoClient = new MongoClient(
            MovieDBSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                MovieDBSettings.Value.DatabaseName);

            _movieCollection = mongoDatabase.GetCollection<Movie>(
                MovieDBSettings.Value.DBCollectionName);
        }

        public async Task<List<Movie>> GetAsync() =>
        await _movieCollection.Find(_ => true).ToListAsync();

        public async Task<Movie?> GetAsync(string id) =>
            await _movieCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public async Task CreateAsync(Movie newMovie) =>
            await _movieCollection.InsertOneAsync(newMovie);

        public async Task UpdateAsync(string id, Movie updatedMovie) =>
            await _movieCollection.ReplaceOneAsync(x => x.Id == id, updatedMovie);

        public async Task RemoveAsync(string id) =>
            await _movieCollection.DeleteOneAsync(x => x.Id == id);

    }
}

Page: Final page name Program.cs

using Microsoft.EntityFrameworkCore;
using MVCCoreApi.Models;
using MVCCoreApiMovie.Models;
using MVCCoreApiMovie.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.Configure<MovieDBSettings>(
    builder.Configuration.GetSection("MovieStoreDatabase"));

//Added Movie Service
builder.Services.AddSingleton<MovieService>();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

builder.Services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));


builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();



Now, your code is ready. All you have to do is make a build and see how it works. Run in local and try out different methods of CRUD operations. Good luck!

Comments

Popular posts from this blog

How to fix Azure DevOps error MSB4126

How to create Custom Visuals in Power BI – Initial few Steps

How to fix Azure DevOps Error CS0579