Apr 30, 2016

How to get JSON POST body on Asp.Net MVC

How to get JSON POST body on Asp.Net MVC controller action. There is two way to get POST data on controller method.

Following is a JSON POST data and assume we are passing this data on the body part.

{
        "Name": "Team Name",
        "Lat": 29.723169,
        "Lng": -95.514999,
        "ShiftEndTime": 1000,
        "ShiftStartTime": 0
    }

And the following class is your Model.

public class TeamViewModel
    {
 public long TeamId { get; set; }
        public string Name { get; set; }
        public double Lat { get; set; }
        public double Lng { get; set; }
        public TimeSpan ShiftStartTime { get; set; }
        public TimeSpan ShiftEndTime { get; set; }
    }

Let's see one by one method to get JSON body POST data.

Refer image and see highlighted yellow mark
1. Select POST method
2. Highlighted body section and selected raw data
3. selected raw data with "Application/JSON" as type
4. Underbody selection writes your JSON object

1. As a Parameter
  • Generally, this method is used in most in normal cases so we can see in MVC this is the default case to get JSON POST data from the body as a parameter.

public ActionResult Index(TeamViewModel model)
    {
       //TODO
    //Write your code here
    
 }

You can see here TeamViewModel pass as a parameter and then utilize for further logic.

2. From Request Object

  • Generally, this kind of cases used when directly post request from other pages or same kind of requirement.
public ActionResult Index()
{
            
            Stream req = Request.InputStream;
            req.Seek(0, System.IO.SeekOrigin.Begin);
            string json = new StreamReader(req).ReadToEnd();

            PlanViewModel plan = null;
            try
            {
                // assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
                plan = JsonConvert.DeserializeObject<TeamViewModel>(json);
            }
            catch (Exception ex)
            {
                // Try and handle malformed POST body
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
   
     //TODO:: you can write your logic here
   

}

You can see the code, get JSON POST data from the Request object. Once you read StreadReader object and converted into the string.

Then string will convert into TeamViewModel object help of JsonConvert.DeserializeObject method and finally get the TeamViewModel object.

Hope you enjoy this post and learn something.

Please post your suggestion in comment section.

Apr 24, 2016

How to consume RESTful service from the client

We have discussed, How to create RESTful service in my previous blogs.

Today, We are talking about how to consume RESTful service from the client.

API call using HTTP Methods for RESTful Services

We will cover most uses methods like GET, POST, PUT and DELETE only.

For example purpose, I have created one API solution and will use for following examples.

Postman is using as a REST Client and consumes REST API service.

1. POST
 - Using POST request we are going to add new products.
 - Open Postman client from chrome browser addon (Note: You can use any REST client for RESTful service)





Check yellow highlighted section from top to bottom.
1. First, select POST from select box
2. Add headers as we know we are talking about RESTful services so JSON format came into pictures.
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
4. Now time to add your request data on body section. (ref. Images)

2. GET
 - Using GET request we are getting existing product data.


1. First, select GET from select box
2. Add URL on URL box ref. image.
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
3. Click on send button and you will get the result on box section

3. PUT
- Using PUT request we are going to update existing record.


1. First, select PUT from select box
2. Add URL on URL box with product id( ref. image).
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
4. Product existing data as a JSON format add on body section
3. Click on the send button and you will see record will be updated.

4. DELETE
- Using DELETE request we are going to delete existing record.


1. First, select DELETE from select box
2. Add URL on URL box with product id (ref. image).
3. Add Content-Type as "application/json" and Accept as "applicaiton/json".
3. Click on the send button and delete existing record from the database.

These simple baby steps post help to a newbie on RESTful service.

Give your suggestion for better improvements on the comment section.

Apr 22, 2016

How to save keystroke during the development using Visual Studio

Today, I am going to share my experience with Visual Studio and how to save keystroke during the development.

Why I am writing this post because of recently I had attended Global Azure BootCamp and that I had enjoyed and learned lot of thing but one of the things was inspired me. It's a Mahesh Dhola session and he had one thought about save keystroke.

So that I had decided to write a post on this and share this good thought to others.

I know experienced developer know the shortcuts and some tricky magic with Visual Studio but this is help for beginner or newbie to Visual Studio.

Let's start one magic and save keystroke during development on visual studio.
  1. When you are creating class also need to write a constructor. So for constructor you just need to write "ctor" and press tab key so constructor will ready for you.
    Before "ctor"
    
    After
    
    Public Student(){
    
    }
    
  2. When you want to create a new property you just need to write "prop" and press twice tab key and property ready for you.
    Before "prop"
    
    After
    
    public TYPE NAME { get; set; }
    
  3. When you want to write try .. catch block then just write try and press tab key twice.
    Before "try"
    
    After
    
      try 
     {         
      
     }
     catch (Exception)
     {
      
      throw;
     }
    
  4. If you want to write any block statement like if, switch, for etc. so visual studio have one interesting feature "Surround with" just press CTL + K + S and open a dialog to choose your block statement and it will prepare skeleton for you.
  5. If you want to write any HTML tag then just you need to right <input and press tab key twice and it will prepare skeleton for you.
    <input
    
  6. When you want to open and collapse any code of block  just press CTL + M twice.
    CTL + M twice
    
  7. When you want to a proper structure in a format, just press CTL + K + D.
    CTL + K + D
    
  8. When you want to find closing brackets just press CTL + } (end bracket).
    CTL + }
    
  9. When you want to move your cursor back just press CTL + - (minus).
    CTL + - (minus)
    
  10. When you want to move your cursor forwards just press CTL + Shift + - (minus).
    CTL + Shift + - (minus)
    
  11. When you want to comment a code block just press CTL + K + C
    CTL + K + C
    
  12. When you want to uncomment a code block just press CTL + K + U
    CTL + K + U
    

There are many magic shortcuts on Visual Studio. Please visit for more shortcuts http://visualstudioshortcuts.com/2015/

Hope this post will help to someone and also share your thoughts in a comment so I will incorporate into this post and that will help to others.

Apr 19, 2016

How to create RESTful API with MVC 6 and Asp.Net Core 1.0

Going to create RESTful API using ASP.NET Core 1.0 or MVC 6. I assume, you know the RESTful API so I am not going to explain what is the RESTful Service / API in this article.

We are talking about MVC 6 and Asp.Net core 1.0. just for your information if you don’t know that like MVC 6 is a part of Asp.Net core 1.0 and it is a completely new unified framework for writing server side web applications and APIs.

One of the changes in MVC 6 is a separation of Asp.Net MVC  and Web API is now past and merge into one. I thought it is good to having a look what changed has made to creating a RESTful API in MVC 6.

Let's start with simple CRUD (Create, Read, Update, Delete) operation in MVC 6 API.

Following  below steps to create RESTful API in MVC 6 with Visual Studio 2015.

Step 1: Create a new project using visual Studio 2015.
  - Open Visual Studio 2015 and go to file section and select New Project.

Step 2: Here you can choose ASP.NET 5 templates.


  - As I already mention MVC 6 has removed the separation of web controller and API controller and combine into one. So it's no matter which application you choose.
  - Yes, If you have a specific requirement like just want to create RESTful API then also ASP.NET 5 templates fulfill your requirement.

Step 3: Once solution created, you will notice few new things come up with default solution and few things have been removed.

  • App_Data, App_Start and Global.asax have been removed.
  • New *.Json file have been added.
  • Added new folders wwwroot and Dependencies
 Step 4: Build the solution and restore the packages during the build process.
  -  Please check output window for build process and check solution has built successfully.

Step 5: You need to add Model for this exercise which is a Student.
  - Student Model have following property
        a. StudentId
        b. Name
        c. SurName


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RESTfulAPI.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
    }
}


Step 6: Now create a new controller for Student API, Select API Controller.


Write controller name as per your requirement.

 

Step 7: Once added API controller. You will get ready API controller.
  - MVC 6 and Visual Studio 2015 provide the scaffolding of RESTful API.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using RESTfulAPI.Models;

namespace RESTfulAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/Students")]
    public class StudentsController : Controller
    {
        private ApplicationDbContext _context;

        public StudentsController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/Students
        [HttpGet]
        public IEnumerable GetStudent()
        {
            return _context.Student;
        }

        // GET: api/Students/5
        [HttpGet("{id}", Name = "GetStudent")]
        public async Task GetStudent([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            Student student = await _context.Student.SingleAsync(m => m.StudentId == id);

            if (student == null)
            {
                return HttpNotFound();
            }

            return Ok(student);
        }

        // PUT: api/Students/5
        [HttpPut("{id}")]
        public async Task PutStudent([FromRoute] int id, [FromBody] Student student)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            if (id != student.StudentId)
            {
                return HttpBadRequest();
            }

            _context.Entry(student).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return HttpNotFound();
                }
                else
                {
                    throw;
                }
            }

            return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
        }

        // POST: api/Students
        [HttpPost]
        public async Task PostStudent([FromBody] Student student)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            _context.Student.Add(student);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (StudentExists(student.StudentId))
                {
                    return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("GetStudent", new { id = student.StudentId }, student);
        }

        // DELETE: api/Students/5
        [HttpDelete("{id}")]
        public async Task DeleteStudent([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            Student student = await _context.Student.SingleAsync(m => m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }

            _context.Student.Remove(student);
            await _context.SaveChangesAsync();

            return Ok(student);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _context.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool StudentExists(int id)
        {
            return _context.Student.Count(e => e.StudentId == id) > 0;
        }
    }
}




Step 8: Now time to access RESTful API from POSTMAN.
- You can consume RESTful API from any source and get the result.

Hope this will help you to create your first RESTful API using MVC 6 and ASP.NET Core 1.0.

Apr 17, 2016

Global Azure Bootcamp 2016 Ahmeadbad - Organized by Ahmedabad User Group

It was my pleasure to attended Global Azure Bootcamp 2016 organized by Ahmedabad User Group.

It was fun and knowledge sharing session was taken by all speakers.


Full day enjoyed with different session and was truly amazed.

I was reached at 10 am in the morning at a venue and organized very well by Ahmedabad User Group.



Mahesh has started with welcome speech to all participate.


First session was taken by my friend Jalpesh about Azure DocumentDB


Then Jagdish has take over the stage for next session and he has taken session about Azure mobile services.


After Jagdish session, it was a lunch time.






After lunch, post lunch session was taken by Sanket Shah about Architecting Modern solution on Azure. He had some fun with coding and tool.



After that, we had Kaushal Bhavsar session and he had taken about secure two-factor authentication with Azure technologies. He had presented the live demo on Azure.


It was time to last session and it was taken by Mahesh Dhola about DevOps and Microsoft Azure. He had some fun with the white board and provided old and new technologies term.



After the end of the almost everyone getting some sort of virtual gift from Global Azure Bootcamp 2016 sponsor by lucky draw.

I am also a lucky guy to get some reward as a form of www.azuredockit.com 1 year licence.


Really it was very fun event and enjoyed a lot. !!


Apr 15, 2016

Let us visit - Global Azure Bootcamp 2016 Organized by Ahmedabad User Group

It's time to be part of  the largest community event in the world. If you are existing about the event? If yes,then Global Azure boot camp 2016 is there. Ahmedabad User group is going to organize Global Azure boot camp.



It is very exciting news from Global Azure BootCamp because it is going to organize more than 180 plus location worldwide.

Please visit the following link for more information

http://global.azurebootcamp.net/

If you want to be a participate in that event then you will need to be a self-registration from below URL.

gab16aug.eventbrite.com

I will be there in the event and my friend going to a speaker on that event. So I waiting for the moment and countdown begin.

Will meet you at Global Azure BootCamp!!


Apr 14, 2016

How to use and configuration session in Asp.Net 5 and MVC 6

In ASP.NET 5, application state can be managed in a variety of ways, depending on when and how the state is to be retrieved.

Here we will be talking about session state configuration and uses.

Please download the sample application from below links.

https://github.com/kalpeshsatasiya/aspnet5session

In Asp.Net 5 for the session need to add session package that provides middleware for managing session state

For package installation, Just need to include reference of following packages in your project.json file.
"Microsoft.AspNet.Session": "1.0.0-rc1-final",
"Microsoft.Extensions.Caching.Memory": "1.0.0-rc1-final"

Once the package is restored, Now time to configure session on startup.cs class page.

For session configuration first need to setup cache because of a session is built on top of IDistributedCache.

For Cache and Session configuration need to add following statements on ConfigureServices method.
services.AddCaching();
services.AddSession();

And one more statement needs to add on Configure method.
 app.UseSession();
Once a session is installed and configured, you refer to it via HttpContext and use the session.
 ///Set Session values
  HttpContext.Session.SetInt32("UserId", 1);
  HttpContext.Session.SetString("UserName", "Kalpesh");

  ///Get Session Values
  ViewBag.UserId = HttpContext.Session.GetInt32("UserId");
  ViewBag.UserName = HttpContext.Session.GetString("UserName");



You can use easy to get and set data on the session to primitive data type. Complex object not directly store on a session. The session will work with byte[] no object.

If you want to store object data into session then it will require serialize the object to a byte[] in order to store them.

Hope you help for understanding session state in asp.net 5 and keep reading.

Apr 13, 2016

SET NOCOUNT ON improve SQL Server store procedure performance

Whenever we write the store procedure to make sure SET NOCOUNT is always ON because when SET NOCOUNT OFF then each store procedure statement sending some message back to client and which is not require on all case.
SET NOCOUNT ON

If you require affect row count without SET NOCOUNT ON  then you just need to require add @@ROWCOUNT after statement of execution. So @@ROWCOUNT will return the result of affected record count.
UPDATE student SET Name= 'Kalpesh'
where studentid = 1



PRINT(@@ROWCOUNT)

When you working on Management Studio and require the message on output window then it will be good to SET NOCOUNT OFF because that we require for development purpose only.
SET NOCOUNT OFF

UPDATE student SET Name= 'Kalpesh'
where studentid = 1
 

When we create new store procedure from SQL Server management studio at time store procedure default template also set a SET NOCOUNT ON.
-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:  
-- Create date: 
-- Description: 
-- =============================================
CREATE PROCEDURE  
 -- Add the parameters for the stored procedure here
 <@Param1, sysname, @p1>  = , 
 <@Param2, sysname, @p2>  = 
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
 SET NOCOUNT ON;

    -- Insert statements for procedure here
 SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
END
GO
asdas

Apr 12, 2016

What is Project.json file in Asp.Net 5

Today, I am going to cover bit explanation for project.json file.

This is the one of the most existing change has made by Microsoft in Asp.Net 5. Which is an introduction of project.json file.

Project.json file manage many configuration sections like dependencies, commands, dynamic frameworks, exclude, publishExclude and scripts executing at different events.

Let's check step by step by step.

Step 1. Open visual studio 2015 and create a new project from File -> New Project -> Select ASP.NET web application.

Step 2. Select Asp.Net 5 template and choose the web application.

Once solution is ready to work but you will try to found web.config file. but "Web.Config" gone now and that is the easiest way to manage configuration on asp.net 5

Step 3. You will check project.json file on root level and double click on it and see what inside it.

You will find the file is divided in various section like dependencies, commands etc..

{
  "userSecretsId": "aspnet5-EF7Migration-fceaa439-1593-4551-962c-4521fb028fd7",
  "version": "1.0.0-*",
  "compilationOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "EntityFramework.Commands": "7.0.0-rc1-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel",
    "ef": "EntityFramework.Commands"
  },

  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  },

  "exclude": [
    "wwwroot",
    "node_modules"
  ],
  "publishExclude": [
    "**.user",
    "**.vspscc"
  ],
  "scripts": {
    "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ]
  }
}

- Dependencies
In dependencies section you can add project dependency and Nuget packages. That is easy to configure the dependencies.

- Commands
This section allows you to define commands for your project, which later on you can execute using dnx

- Frameworks
Asp.Net support mulitple frameworks and which will use dynamic framework based on housting.

- Exclude
This section indicate to that folder which will be not part of publicing website. It means those folder will be exculded from publising website.

- PublishExclude
This is very similar to exclude but publish exculde support folder and files both.

- Scripts
Script tag use for specific build automation script can excute before publishing the website. There is ain mention under"prepublish" and "postpublish".




Apr 10, 2016

Asp.Net 5 Database Migrations in EF7

Today, I am going to cover. How database migrations work in EF7 on the new platform of asp.net 5.

I have created a sample application with Product table. you can find the code from https://github.com/kalpeshsatasiya/EF7Migration

Let's start step by step

Step 1. Create a new project from visual studio 2015 and select asp.net 5 template.

Step 2. Once project created, Open a project.json file and check Entity Framework 7 dependency added or not. if dependency already added then you will see the following line under the "dependencies" tag. if not then add Entity Framework 7 using NuGet package.

"EntityFramework.Commands": "7.0.0-rc1-final"


Step 3. Once EF7 is on the place then move to appsettings.json file for the connection string. Update connection string as per your requirement.


Step 4. Now build the application and check solution is build successfully or not.

Step 5. Check Migration folder at the root level and expand it. you will see the migration script already created by the solution for default identity tables.

Now you need to require update database for that migration script. so you need to run the following command on package manager console.

Before executing any command. please check dnx command working or not.
dnx ef database update

Step 6. Till here we are just looking update the database but now let's check how to migrate the database (I meant how to add/remove fields from existing table)

Step 7. In our example, I have added a new table for the product so need to create migration script for product table.

Following commands need to execute for creating migrations script and update database for same.

dnx ef migrations add [migration name] 


dnx ef database update

Hope you like the cutting edge technology blog post. This post is very useful to newbie in asp.net 5 / Entity Framework 7.

Apr 9, 2016

How to use Object Mapper Mapster in Asp.Net 5 or MVC 6

Today, I am going to explain how to use Mapster in asp.net 5 or MVC 6 application. How to a configuration.

It's very simple and it hardly takes only 2 min to configure Mapster in Asp.Net 5 application.

Let's start step by step configuration.

1. Create new Web Application from visual studio 2015 using Asp.Net 5 template.

2. Once a solution is created and ready for work then install Mapster from NuGet package or Package Manger Console

 install-package Mapster 

3. Once Mapster installed. Open a startup.cs page from the root.



4. Add Mapster reference on Startup.cs page.
 Using Mapster 

5. Now Goto constructor of Startup.cs page and add Mapster configuration. Refer image for more detail.
 TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true); 

6. Once done configuration on startup.cs page then you are ready to use Mapster for object mapping.

7. Let's see an example how to use Mapster after configuration.

8. Added following classes on solution.
     1. Under Models folder added Student.cs model
     2. Under Services folder added IStudentService.cs and StudentService.cs
     3. Under ViewModels folder added StudentViewModel.cs
     4. Under Controller folder added StudentController.cs


9. Very simple to use Mapster for object mapper. Just see in StudentController on Index method were student service call the GetAll method which returns all students data.

but before we move ahead I assume you know about Dependancy Injection in Asp.Net 5 which is inbuilt in the framework.

 public IEnumerable Index()
        {
            var students = _studentService.GetAll();
            return students.Adapt, IEnumerable>();
        } 

For more detail please refer screenshots.


You can download solution from my repository.
https://github.com/kalpeshsatasiya/MapsterObjectMapper

For more details about Mapster please visit https://github.com/eswann/Mapster.




Apr 4, 2016

How to get AppSettings values from appsettings.json file in MVC 6

Today, I am going to cover the latest and cutting edge technology related point.

That is an ASP.NET Core 1.0 (MVC 6) from Microsoft.

Here I am sharing my experience with you for MVC 6 application. We know in the previous version for MVC application, we have web.config file but in the newer version of MVC application, we don't have.

In MVC 6 configuration managed by.json file so when you create a new application for ASP.NET 5 (ASP.NET CORE 1.0) at the time you will see few .json file in solution explorer.

One of the JSON file names is appsettings.json which we can similar to web.config file from the previous version of the application.

So we can configure all setting under the appsettings.json file like connection string and custom settings.

More talking about AppSettings tag under the appsettings.json file where we can set custom key/value data which will be used later in the application.

Here we can see step by step configuration and how to read the AppSettings values.

1. How to set AppSettings in appsettings.json file.

Added few settings 1. WebSiteURL and 2.WebSiteTitle.

2. How to configure in Startup,cs file
Added service configuration under the ConfigurationService method as a display in the image.

3. Added model for AppSettings values. So before adding configuration on Startup page we require one model which has same property name declare's in AppSettings.


4. How to used in the controller with dependency inject.

Pass parameter IOptions settings in controller constructor for dependency injection.

Under the constructor, assign values to local variables and use in the controller actions. you can see in screenshots. we have assign value into ViewBag for WebSiteURL and WebSiteTitle and display on view.