Tuesday 7 November 2023

ASP.NET Core Web API and MongoDB step by step Example

 We can see below service example step by step:


--Open Visual Studio 2022 & give the name as 'DotNetCoreWebAPI'

--Then install 'MongoDB.Driver' in Nuget Package
-I-Then create 'Models' folder>>ProjectInfo.cs add below code snippet

using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;

namespace DotNetCoreWebAPI.Models
{
    public class ProjectInfo
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string? _id { get; set; }
        
        public int ProjID { get; set; }

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

        public string ProjType { get; set; }
        public int __v { get; set; }
    }
}

-II-Then create 'Models' folder>>ProjectInfoDatabaseSettings.cs add below code snippet

namespace DotNetCoreWebAPI.Models
{
    public class ProjectInfoDatabaseSettings
    {
        public string ConnectionString { get; set; } = null!;

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

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

-III-Then create 'Services' folder>>ProjectInfoService.cs add below code snippet

using DotNetCoreWebAPI.Models;
using Microsoft.Extensions.Options;
using MongoDB.Driver;

namespace DotNetCoreWebAPI.Services
{
    public class ProjectInfoService
    {
        private readonly IMongoCollection<ProjectInfo> _projectinfoCollection;
        public ProjectInfoService(
        IOptions<ProjectInfoDatabaseSettings> projinfoDatabaseSettings)
        {
            var mongoClient = new MongoClient(
                projinfoDatabaseSettings.Value.ConnectionString);

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

            _projectinfoCollection = mongoDatabase.GetCollection<ProjectInfo>(
                projinfoDatabaseSettings.Value.ProjectInfoCollectionName);
        }
        public async Task<List<ProjectInfo>> GetAsync() =>
        await _projectinfoCollection.Find(_ => true).ToListAsync();

        public async Task<ProjectInfo?> GetAsync(string id) =>
        await _projectinfoCollection.Find(x => x._id == id).FirstOrDefaultAsync();

        public async Task CreateAsync(ProjectInfo newProjectInfo) =>
        await _projectinfoCollection.InsertOneAsync(newProjectInfo);

        public async Task UpdateAsync(string id, ProjectInfo updatedProjectInfo) =>
        await _projectinfoCollection.ReplaceOneAsync(x => x._id == id, updatedProjectInfo);

        public async Task RemoveAsync(string id) =>
        await _projectinfoCollection.DeleteOneAsync(x => x._id == id);
    }
}

-IV-Then in 'appsettings.json' add below code snippet

{
  "ABCBuildersDatabase": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "ABCBuilders",
    "ProjectInfoCollectionName": "ProjectInfo"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

-V-Then in Controller folder>> 'ProjectInfoController.cs'  add below code snippet

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

namespace DotNetCoreWebAPI.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProjectInfoController : ControllerBase
    {
        private readonly ProjectInfoService _projinfoService;

        public ProjectInfoController(ProjectInfoService piService) =>
            _projinfoService = piService;

        [HttpGet]
        public async Task<List<ProjectInfo>> Get() =>
        await _projinfoService.GetAsync();

        [HttpGet("{id:length(24)}")]
        public async Task<ActionResult<ProjectInfo>> Get(string id)
        {
            var projI = await _projinfoService.GetAsync(id);

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

        [HttpPost]
        public async Task<IActionResult> Post(ProjectInfo newProjectInfo)
        {
            await _projinfoService.CreateAsync(newProjectInfo);

            return CreatedAtAction(nameof(Get), new { id = newProjectInfo._id }, newProjectInfo);
        }

        [HttpPut("{id:length(24)}")]
        public async Task<IActionResult> Update(string id, ProjectInfo updatedProjectInfo)
        {
            var pi = await _projinfoService.GetAsync(id);

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

            updatedProjectInfo._id= pi._id;

            await _projinfoService.UpdateAsync(id, updatedProjectInfo);

            return NoContent();
        }

        [HttpDelete("{id:length(24)}")]
        public async Task<IActionResult> Delete(string id)
        {
            var book = await _projinfoService.GetAsync(id);

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

            await _projinfoService.RemoveAsync(id);

            return NoContent();
        }

    }
}

-VI-Then at last configure services in 'Program.cs' file

using DotNetCoreWebAPI.Models;
using DotNetCoreWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddSingleton<ProjectInfoService>();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
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();

--Then Build and Run the application to check the services using Swagger as well as in Postman


















No comments:

Post a Comment