ASP.net MVC authentication with Mongodb Tutorial from Asp.net Development company

Asp.net development company experts will explain the process of MVC authentication MongoDb. You will learn how to create web API using asp.net core. You can read this post and experiment and share your experience.

A new document oriented approach in the databases which follows the NoSQL statement is MongoDB. It is a schema independent method.The schema thus formed can be mapped to the SQL tables. A schema in MongoDB is defined  as a  collection and a record in this schema is called as the document.

The NoSql approach is gaining popularity due to its non relational approach in modern web applications.

Creation of a Web API using ASP.Net Core

The purpose of creating a web API is that it can be used as HTTP services and can be accessed by the client using desktop to mobile devices. Using Web API as a medium, these client apps can easily interact with a NoSQL database like MongoDB.

ASP. Net MVC and MongoDB Implementation

Download MongoDB and Install the database. Once the installation is completed, the system drive will create a MongoDB folder in the following path

C:\Program Files\MongoDB

Also create a data folder where the data will be stored. Let's assume that the data is stored in E drive.the path to locate will be:

E:\MongoDbData\data

Open the Command prompt and navigate to the following folder

C:\Program Files\MongoDB\Server\3.2\bin

Run the command as shown .

C:\ program files\ MongoDB\Server\3.2\bin>mongod -- dpath e:\MongodbData\data

MongoDB on port 27017 will be connected.Open another instance of the command prompt and navigate to the bin folder and run the following command:

C:\Program Files\ Mongodb\Server\3.2\bin>mongo

This will connect to the default test database. Run the command on > (command prompt)

> use EmployeeDB

A database of name EmployeeDB will be created. In this database we are allowed to create a transaction using the following command:

db.createCollection('Products')

The Schema for the Products collection can be written using command from the command prompt

db.Products.insert({'ProductId':1,'ProductName':'Printer All in One','Price':12000,'Category':'IT- product'})

Run the following command

>db.Products.find({})

The following result will be displayed

command-result

The schema will add _id property. This property will be an ObjectId which will be generated automatically.

Creating ASP.NET Web API with MVC 6

Step1: Open Visual Studio  and create a new ASP.NET application 

Step 2: In the new ASP.Net project, add folder and a new class file  containing the code

//***

using System.Collections.Generic; 

namespace WebAPI_WithMVC6.Models

{    public class PersonInfo1

    {

        public int PersonId { get; set; }

        public string PersonName { get; set; }

        public int Age { get; set; }

        public string Gender { get; set; }

        public string City { get; set; }

    }

     public class PersonData : List<PersonInfo1>

    {

        public PersonData()

        {

            Add(new PersonInfo1() { PersonId = 1, PersonName = "XZ", 

                             Age = 26, Gender = "Male", City = "LA" });

            Add(new PersonInfo1() { PersonId = 2, PersonName = "YP", 

                              Age = 32, Gender = "Female", City = "BS" });

            Add(new PersonInfo1() { PersonId = 3, PersonName = "FN", 

                             Age = 42, Gender = "Male", City = "DL" });

                    }

    }

     public class DataAccess

    {

        public static PersonData Persons;

         public DataAccess()

        {            Persons = new PersonData();

        }

         public PersonData Get()

        {

            return Persons;

        }

         public PersonInfo1 Get(int id)

        {

            return Persons.Find(p => p.PersonId == id);

        }

         public PersonData Add(PersonInfo1 p)

        {

            Persons.Add(p);

            return Persons;

        }

         public PersonData Update(int id, PersonInfo1 p)

        {

            var per = Persons.Find(px => px.PersonId == id);

            if (per != null)

            {

                Persons.Remove(per);

                Persons.Add(p);

            }            return Persons;

        }

         public PersonData Delete(int id)

        {

            var per = Persons.Find(px => px.PersonId == id);

            if (per != null)

            {

                Persons.Remove(per);

            }

            return Persons;

        }

    }

}

***//

The above class file contains following classes

• PersonInfo1 - This is the entity class representing schema for the Person information.

• PersonData - This class is derived from List<PersonInfo> class. This class contains constructor with some initialization data.

• DataAccess - This class performs CRUD operations using PersonInfo class.

Step 3: In the project, add a new folder of the name Repository. This will encapsulate the data access layer and contains logic for accessing the DataAccess class. The repository isolates the data access layer from the controller.

using System.Collections.Generic;

using WebAPI_WithMVC6.Models;

 namespace WebAPI_WithMVC6.Repository

{

    public interface IPersonRepository<T, in TPk>  where T : class

    {

        IEnumerable<T> Get ();

        T Get(TPk id);

        IEnumerable<T> Add(T obj);

        IEnumerable<T> Update(TPk id, T obj);

        IEnumerable<T> Delete(TPk id);

    }

     public class PersonRepository : IPersonRepository<PersonInfo1, int>

    {

        DataAccess objds;

        public PersonRepository()

        {            objds = new DataAccess(); 

        }

        public IEnumerable<PersonInfo11> Add(PersonInfo1 obj)

        {

          return  objds.Add(obj);

        }

 

        public IEnumerable<PersonInfo1> Delete(int id)

        {

            return objds.Delete(id);

        }

         public IEnumerable<PersonInfo1> Get()

        {

            return objds.Get();

        }

 

        public PersonInfo1 Get(int id)

        {

            return objds.Get(id);

        }

 

        public IEnumerable<PersonInfo1> Update(int id, PersonInfo1 obj)

        {

            return objds.Update(id, obj);

        }

    }

}

The above code is the most important part of the application.

This code contains the IPersonRepository<T,TPk> interface. This is a generic interface where T is class and TPk is the input parameter which is the going to be the id. The class Person Repository implements IPerson Repository interface and implements its methods. These methods call methods from the DataAccess class which we have created in the Models folder.

Step 4: In the previous step, we have implemented the Repository which this decouples the Data Access from the Controller. To use this Repository, we need to register it in the ASP.NET 5 dependency Injection container. In the project, we have the Startup.cs class containing the Configure Services method. In this method we will register the Repository using the following code:

//***

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddSingleton<IPersonRepository<PersonInfo1, int>,PersonRepository>();
}
***//
Using the AddSingleton() method, we register the Repository in the Dependency Injection. This method will create a singleton instance for the Person Repository object.

Step 5: In the Controllers folder, add a new Web API Controller class as shown in the following image:
This will add a controller with CRUD action methods. Remove the already available code from the class and add the following code in it:

using System.Collections.Generic;
using Microsoft.AspNet.Mvc;
using WebAPI_WithMVC6.Repository;
using WebAPI_WithMVC6.Models;
 namespace WebAPI_WithMVC6.Controllers
{
    [Route("api/[Person]")]
    public class PersonController : Controller
    {
        [FromServices]
        public IPersonRepository<PersonInfo, int> _repository { get; set; }
 
        [HttpGet]
        public IEnumerable<PersonInfo1> Get()
        {
            return _repository.Get();
        }
         [HttpGet("{id}")]
        public PersonInfo1 Get(int id)
        {
            return _repository.Get(id);
        }
         [HttpPost]
        public IEnumerable<PersonInfo1> Post([FromBody]PersonInfo11 p)
        {
            return _repository.Add(p);
        }
         [HttpPut("{id}")]
        public IEnumerable<PersonInfo1> Put(int id, [FromBody]PersonInfo1 p)
        {
            return _repository.Update(id, p);
        }
         [HttpDelete("{id}")]
        public IEnumerable<PersonInfo1> Delete(int id)
        {
            return _repository.Delete(id);
        }
    }
}
In the above code, we have the Route attribute applied on the Controller class. Set the value of the attribute asRoute [“api/Person”]

The above code declares the Repository object using the following code:

[FromServices]
public IPersonRepository<PersonInfo1, int> _repository { get; set; }

The attribute FromServices tell MVC to inject the IPersonRepository in the current controller. The controller class contains methods for HTTP actions for performing CRUD operations.

Step 6: To launch the Person API, we need to make changes in the launchSettings.json file in the Propertiesfolder of the project. Change the profiles, launchUrl property as shown in the following code:

"profiles": {
    "IIS Express": {
      "commandName": "Chrome",
      "launchBrowser": true,
      "launchUrl": "api/Person",
      "environmentVariables": {
        "Hosting:Environment": "Development"
      }
    },

Testing Web API in Fiddler

We will test our Web API using Fiddler. Fiddler is an HTTP debugging proxy server application written by Eric Lawrence. 

Launch Web API using F5. Open the Fiddler tool.

Testing GET Operation

In the Composer tab of the fiddler tool, add the following URL,

http://localhost:1135/api/Person

Set the method as GET and click on the Execute button as shown in the following image:

In the Composer Tab, set the Method as POST, add the following JSON object in the Request body and Content Type as shown in the following image

Click on the Execute Button, the new record will be added and will be shown as per the following image
{}
Age= 26
City= LA
Gender= Male
Personid= 7
PersonName= XZ

Likewise PUT and Delete functionality can be tested.

The ASP.NET Web API Framework is merged in MVC 6 and provides an easy mechanism to create API services which can be consumed by various client applications. The dependency injection helps to isolate the data access from the controllers.

Experts of asp.net development company has just shared this post with developers to assist them in authentication process os asp.net mvc Mongodb. If you have anything to say or ask, write in the comments.

Author Bio: Akshita is working in renowned asp.net development company as a content writer. She has written several articles about java and ASP.NET MVC. You can find more articles of her online.