European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: How To Create ASP.NET Core MVC Application?

clock April 26, 2021 07:06 by author Peter

In this article, we will learn how to create an ASP.NET Core MVC web application step by step. Prior to creating the application, let's know about the ASP.NET Core.

What is ASP.NET Core?
ASP.NET Core is an open source cross platform framework for developing and building web, cloud, IoT applications.
 
Why should we use ASP.NET Core?

  • ASP.NET is an open-source platform that runs on Microsoft .NET Core Framework.
  • We can build and run the ASP.NET core application on a cross platform environment such as Windows, MacOs, Linux etc.
  • We can build modern apps such as Cloud, IoT, Web apps, mobile backend etc. and those can be easily enabled to run over the cloud platform.
  • We can host applications on any modern platform such as docker, AKS, or any environment.
  • Saves the efforts of the developer by built-in features such as dependency injection, you can enable docker, containerization, swagger support in just one click.

 

Now let's start creating an ASP.NET Core MVC web application.
 
Step 1 - Open Visual Studio
Open Visual Studio ( I am using 2019)
Once the Visual Studio Opens, Then click on Continue Without Code as shown in the following image

Then from Visual Studio Menu, click on File => New Project, as shown in the following image

Click on the New Project, then the following window appears as shown in step 2.
 
Step 2 - Choose Project Template
You will see the two project templates,

  • ASP.NET Core Web App: This project template creates the web application with Razor pages without Model, View, Controller.
  • ASP.NET Core Web App (Model-View-Controller): This project template creates the web application with Model, View, Controller (MVC).


Choose the ASP.NET Core Web App(Model-View-Controller) Template as shown in the following image.

After choosing the project template click on Next.
 
Step 3 - Define Project Name and Location
In the project configuration window you will see the following options,
Project Name
Define any name for your project as per your choice.

Location

Choose the location to save the project files on your hard drive of the machine. I have chosen the Project/VS folder of the E drive of the machine, and obviously it's different on your computer.

Solution Name
Solution name is auto-defined based on the project name, but you can change the name based on your own choice.

Additionally, there is a checkbox, if you have checked it, then the solution file (.sln) and project files will be saved in the same folder. Now Choose the minimum details for ease of understanding as shown in the following image.


After defining the required details, click on the Next.
 
Step 4 - Choose the Target Framework
Choose the target framework .NET 5 which is the latest or you can choose based on your requirement, skip the other details for ease of understanding as shown in the following image.

After providing the required details, click the create button. It will create the ASP.NET Core MVC web application as shown in step 5.
 
Step 5 - Understanding ASP.NET Core MVC Folder Structure
The following is the default folder structure of the ASP.NET Core ASP.NET MVC application.

Let's understand preceding project folder structure in brief.
 
The wwwroot folder
The wwwroot is the default root folder for storing the static files related to the project and those files can be accessed programmatically with a relative path.
 
Controller Folder
The controller folder contains the controller classes where the operation related code written.
 
Model Folder
The Models Folder contains the domain or entity classes. Models can be written anywhere in the solution such as in separate class library or folder etc.
 
Views Folder
The Views folder holds the razor pages which are responsible for showing and getting the data from the users.
 
The appsettings.json File
The appsettings.json folder contains the configuration and secret details of the application.
 
Program.cs File

The Program.cs is the starting point of the application which will create the host for an application to run the application.
 
Startup.cs File
The Startup.cs file allows to configure the behaviour of the application such as defining the routes, dependency injection etc.
 
Step 6 - Run the ASP.NET Core MVC Application
You can run the application with default contents or let open the Index.cshtml file and put some contents there. Now press F5 on the keyboard or use the run option from Visual Studio to run the application in the browser.



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Consuming ASP.NET Web API REST Service In ASP.NET MVC Using HttpClient

clock April 20, 2021 08:44 by author Peter

In many forum posts, developers and students have asked one common question, that is, how to use Web API REST Service in ASP.NET MVC application and how to make a call between them to exchange the information. So, considering this demand, I have decided to write this article to demonstrate how to consume ASP.NET Web API REST Service in ASP.NET MVC application with the help of HttpClient.

 
Prerequisites
If you don't know what is Web API REST service and how to create, publish, host ASP.NET Web API REST Service, then please refer to my video as well as articles, using the following links. Also, follow the same sequence if you want to learn web API REST service from creating to hosting to consuming in client application.
    Creating ASP.NET Web API REST Service
    Publishing ASP.NET Web API REST Service Using File System Method
    Hosting ASP.NET Web API REST Service on IIS 10

In this article, we will use the same hosted Web API REST service to consume in our created ASP.NET MVC web application. Now, let's start consuming Web API REST service in ASP.NET MVC application step by step.

Step 1 - Create MVC Application.
    "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".

    Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name as you wish and click OK.

    After clicking, the following Window will appear. Choose empty project template and check on MVC option.

The preceding step creates the simple empty ASP.NET MVC application without Model, View, and Controller, The Solution Explorer of created web application will look like the following.

Step 2 - Install HttpClient library from NuGet
We are going to use HttpClient to consume the Web API REST Service, so we need to install this library from NuGet Package Manager .
 
What is HttpClient?
HttpClient is base class which is responsible to send HTTP request and receive HTTP response resources i.e from REST services.
To install HttpClient, right click on Solution Explorer of created application and search for HttpClient, as shown in the following image.

Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds, depending on your internet speed.
 
Step 3 - Install WebAPI.Client library from NuGet
This package is used for formatting and content negotiation which provides support for System.Net.Http. To install, right click on Solution Explorer of created application and search for WebAPI.Client, as shown in following image.

Now, click on "Install" button after choosing the appropriate version. It will get installed after taking few seconds depending on your internet speed. We have installed necessary NuGet packages to consume Web API REST services in web application. I hope you have followed the same steps.
 
Step 4 - Create Model Class
Now, let us create the Model class named Employee.cs  or as you wish, by right clicking on Models folder with same number of entities which are exposing by our hosted Web API REST service to exchange the data. The code snippet of created Employee.cs class will look like this.
 
Employee.cs
    public class Employee  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
                 
        public string City { get; set; }  
      
    }   


Step 5 - Add Controller Class
Now, let us add ASP.NET MVC controller, as shown in the screenshot given below.

After clicking Add button, it will show in the Window. Specify the Controller name as Home with suffix Controller. Now, let's modify the default code of Home controller .
 
Our hosted Web API REST Service includes these two methods, as given below.

    GetAllEmployees (GET )
    GetEmployeeById (POST ) which takes id as input parameter

We are going to call GetAllEmployees method which returns the all employee details ,The hosted web api REST service base URL is http://192.168.95.1:5555/ and to call GetAllEmployees from hosted web API REST service, The URL should be Base url+api+apicontroller name +web api method name as following,

http://192.168.95.1:5555/api/Employee/GetAllEmployees

In the preceding url

    http://localhost:56290 Is the base address of web API service, It can be different as per your server.
    api It is the used to differentiate between Web API controller and MVC controller request .
    Employee This is the Web API controller name.
    GetAllEmployees This is the Web API method which returns the all employee list.

After modifying the code of Homecontroller class, the code will look like the following.
 
Homecontroller.cs
    using ConsumingWebAapiRESTinMVC.Models;  
    using Newtonsoft.Json;  
    using System;  
    using System.Collections.Generic;  
    using System.Net.Http;  
    using System.Net.Http.Headers;  
    using System.Threading.Tasks;  
    using System.Web.Mvc;  
      
    namespace ConsumingWebAapiRESTinMVC.Controllers  
    {  
        public class HomeController : Controller  
        {  
            //Hosted web API REST Service base url  
            string Baseurl = "http://192.168.95.1:5555/";      
            public async Task<ActionResult> Index()  
            {  
                List<Employee> EmpInfo = new List<Employee>();  
                  
                using (var client = new HttpClient())  
                {  
                    //Passing service base url  
                    client.BaseAddress = new Uri(Baseurl);  
      
                    client.DefaultRequestHeaders.Clear();  
                    //Define request data format  
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
                      
                    //Sending request to find web api REST service resource GetAllEmployees using HttpClient  
                    HttpResponseMessage Res = await client.GetAsync("api/Employee/GetAllEmployees");  
      
                    //Checking the response is successful or not which is sent using HttpClient  
                    if (Res.IsSuccessStatusCode)  
                    {  
                        //Storing the response details recieved from web api   
                        var EmpResponse = Res.Content.ReadAsStringAsync().Result;  
      
                        //Deserializing the response recieved from web api and storing into the Employee list  
                        EmpInfo = JsonConvert.DeserializeObject<List<Employee>>(EmpResponse);  
      
                    }  
                    //returning the employee list to view  
                    return View(EmpInfo);  
                }  
            }  
        }  
    }


I hope, you have gone through the same steps and understood about the how to use and call Web API REST service resource using HttpClient .
 
Step 6 - Create strongly typed View
Now, right click on Views folder of the created application and create strongly typed View named by Index by choosing Employee class to display the employee list from hosted web API REST Service, as shown in the following image.

Now, click on "Add" button. It will create View named index after modifying the default code. The code snippet of the Index View looks like the following.

Index.cshtml
    @model IEnumerable<ConsumingWebAapiRESTinMVC.Models.Employee>  
      
    @{  
        ViewBag.Title = "www.compilemode.com";  
    }  
      
    <div class="form-horizontal">  
      
        <hr />  
        <div class="form-group">  
      
      
            <table class="table table-responsive" style="width:400px">  
                <tr>  
                    <th>  
                        @Html.DisplayNameFor(model => model.Name)  
                    </th>  
                    <th>  
                        @Html.DisplayNameFor(model => model.City)  
                    </th>  
                      
                </tr>  
      
                @foreach (var item in Model) {  
                    <tr>  
                        <td>  
                            @Html.DisplayFor(modelItem => item.Name)  
                        </td>  
                        <td>  
                            @Html.DisplayFor(modelItem => item.City)  
                        </td>  
                          
                    </tr>  
    }  
      
            </table>  
        </div>  
    </div>


The preceding View will display all employees list . Now, we have done all the coding.

Step 7 - Run the Application



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in