ASP.NET Core web API
Open visual studio and create project which is of category “asp.net core web api”. Then remove unnecessary .cs files like controllers or others. Then create folders “DataAccessLayer” for writing code related to data accessing and “Model”. Then create a new controller like “CrudOperationContoller.cs” and create new data access files (ICrudOperationDL.cs , CrudOperationDl.cs implemented class for interface ICrudOperationDL)in DataAccessLayer folder. Then add dependency injection for controller file of interface ICrudOperationDL.cs file as below
private readonly ICrudOperationDL _crudOperationDL;
public CrudOperationController(ICrudOperationDL crudOperationDL)
{
_crudOperationDL = crudOperationDL;
}Then add dependecy injection for CrudOperationDL.cs of configartion to retrive the configuration values like to establish connection with mongodb etc.
private readonly IConfiguration _configuration;
public CrudOperationDL(IConfiguration configuration)
{
_configuration = configuration;
}Then create a model for data insertion operation like “InsertRecord.cs” then define classes for request and response as below
using MongoDB.Bson.Serialization.Attributes;
using System.ComponentModel.DataAnnotations;
namespace CRUD_operations_API.Model
{
public class InsertRecordRequest
{
[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string Id { get; set; }
public string CreatedDate { get; set; }
public string UpdatedDate { get; set; }
[Required]
[BsonElement("Name")]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Contact { get; set; }
public int Salary { get; set; }
}
public class InsertRecordResponse
{
public bool IsSuccess { get; set; }
public string Message { get; set; }
}
}Then write http post method functionality as InsertRecord(here it is an api controller for inserting record). Here the method will take req as parameter and give an actionresult as output it innclude response. Here in this we create a new object for InsertRecordResponse and return this response as an action. We shoul mention the function as async otherwise it show error because it should wait for a response.
using CRUD_operations_API.DataAccessLayer;Get K LAKSHMAN’s stories in your inbox
Join Medium for free to get updates from this writer.
using CRUD_operations_API.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CRUD_operations_API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CrudOperationController : ControllerBase
{
private readonly ICrudOperationDL _crudOperationDL;
public CrudOperationController(ICrudOperationDL crudOperationDL)
{
_crudOperationDL = crudOperationDL;
}
[HttpPost]
public async Task<IActionResult> InsertRecord(InsertRecordRequest req)
{
InsertRecordResponse res= new InsertRecordResponse();
try
{
}
catch(Exception ex)
{
res.IsSuccess = false;
res.Message = "Exception occures "+ex.Message;
}
return Ok(res);
}
}
}
Add the database details in appsettings.json file
{
"DatabaseSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "CrudOperation",
"CollectionName": "UserDetails"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}Here we have to install MonogoDB.Driver package. Goto tools- > Nuget package manager ->manage packages -> search for it and install. Then update the CrudOperationDL file for establishing connection to mongodb and retrieve database, collection. Then Add a method which is InsertRecord as abstract method in interface(ICrudOperationDL) then implement it in the implementation class.
using CRUD_operations_API.Model;
using MongoDB.Driver;
namespace CRUD_operations_API.DataAccessLayer
{
public class CrudOperationDL : ICrudOperationDL
{
private readonly IConfiguration _configuration;
private readonly MongoClient _mongoclient;
private readonly IMongoCollection<InsertRecordRequest> _mongoCollection;
public CrudOperationDL(IConfiguration configuration)
{
_configuration = configuration;
_mongoclient = new MongoClient(_configuration["DatabaseSettings:ConnectionString"]);
var _MongoDatabase = _mongoclient.GetDatabase(_configuration["DatabaseSettings:DatabaseName"]);
_mongoCollection = _MongoDatabase.GetCollection<InsertRecordRequest>(_configuration["DatabaseSettings:CollectionName"]);
}
public async Task<InsertRecordResponse> InsertRecord(InsertRecordRequest Req)
{
InsertRecordResponse res = new InsertRecordResponse();
try
{
}
catch (Exception ex)
{
res.IsSuccess = false;
res.Message = "Exception occurs " + ex.Message;
}
return res;
}
}
}Now we have to link this InsertRecord Function with the CrudOperationController and also we have to intialize the IsSuccess and Message variables in response object and then we have to call the methos and get the returned value from the method and store it in res. In this statement we have to mention await since it need to wait for the data. And we have to update route [Route(“api/[controller]/[Action]”)] so that we get multiple action contollers.
using CRUD_operations_API.DataAccessLayer;
using CRUD_operations_API.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CRUD_operations_API.Controllers
{
[Route("api/[controller]/[Action]")]
[ApiController]
public class CrudOperationController : ControllerBase
{
private readonly ICrudOperationDL _crudOperationDL;
public CrudOperationController(ICrudOperationDL crudOperationDL)
{
_crudOperationDL = crudOperationDL;
}
[HttpPost]
public async Task<IActionResult> InsertRecord(InsertRecordRequest req)
{
InsertRecordResponse res= new InsertRecordResponse();
res.IsSuccess = true;
res.Message = "Inserted Successfully...";
try
{
res= await _crudOperationDL.InsertRecord(req);
}
catch(Exception ex)
{
res.IsSuccess = false;
res.Message = "Exception occures "+ex.Message;
}
return Ok(res);
}
}
}Now in CrudOperationDL we can modify the data from request body as our wish in InsertRecord function and then by using collection object (already retrieved by using _configuration and mongodb connection) we can insert document into the collection.
using CRUD_operations_API.Model;
using MongoDB.Driver;
namespace CRUD_operations_API.DataAccessLayer
{
public class CrudOperationDL : ICrudOperationDL
{
private readonly IConfiguration _configuration;
private readonly MongoClient _mongoclient;
private readonly IMongoCollection<InsertRecordRequest> _mongoCollection;
public CrudOperationDL(IConfiguration configuration)
{
_configuration = configuration;
_mongoclient = new MongoClient(_configuration["DatabaseSettings:ConnectionString"]);
var _MongoDatabase = _mongoclient.GetDatabase(_configuration["DatabaseSettings:DatabaseName"]);
_mongoCollection = _MongoDatabase.GetCollection<InsertRecordRequest>(_configuration["DatabaseSettings:CollectionName"]);
}
public async Task<InsertRecordResponse> InsertRecord(InsertRecordRequest Req)
{
InsertRecordResponse res = new InsertRecordResponse();
try
{
Req.CreatedDate = DateTime.Now.ToString();
Req.UpdatedDate = "";
await _mongoCollection.InsertOneAsync(Req);
}
catch (Exception ex)
{
res.IsSuccess = false;
res.Message = "Exception occurs " + ex.Message;
}
return res;
}
}
}



