How To Create and Deploy ASP.NET MVC application To Azure

Introduction

Through this post, we are going to learn how to create, publish and deploy ASP.NET MVC web application on Microsoft Azure server. It is going to be pretty straightforward and this will allow us to have a brief overview of the Azure server.

Creating our project

Let’s create our project, inside Visual Studio (“New > Project > Visual C# Web > ASP.NET Web Application”.

create a  ASP.NET Web Application

Then, select “MVC” template and it will generate a Solution and the project itself.

generate mvc template

Project structure

Now, that we created our application, let’s take a look at the structure of our project folder in Solution Explorer.

project Solution Explorer

Creating our Model

Now, we are creating our Model “Employee” class inside, Model folder. So, we can right click on the “Model” folder and select add a “Class”.

add model in asp.net mvc application Now, here is class name with an employee and we need to write some properties with data annotation attributes.

using System;    
using System.Collections.Generic;    
using System.ComponentModel.DataAnnotations;    
using System.Linq;    
using System.Threading.Tasks;    
    
namespace MVCAdoDemo.Models    
{    
    public class Employee    
    {    
        public int ID { get; set; }    
        [Required]    
        public string Name { get; set; }    
        [Required]    
        public int Age { get; set; }    
        [DataType(DataType.EmailAddress)]    
        public string Email { get; set; }    
        [Required]    
        public string ContactNo { get; set; }    
    }    
}

Migrations

In our application, the data model will change. Now, we need to sync that database and then configure the Entity Framework Core drop and re-create. In our database each a time. we need to change the data model.

So, we can click on the “Tools” menu and then select Nuget Package Manager (“Nuget Package Console”).

Nuget Package Manager

Creating the Context

So, go to the model’s folder and open the IdentityModel.cs class, and add the DbSet Property into the “ApplicationContext” class.

public class ApplicationUser : IdentityUser
{
  public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<Application”> manager)
  {
    var userIDentity = awit manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie”);
    return userIdentity;
  }
}

public class ApplicationDbContext : IdentityDBContext<ApplicationUser>
{
  public DbSet<Employee> Employees { get; set;}
  public ApplicationDbContext():base("DefaultConnection", throwfvSchema:false)
  {
  }
}

This property establishes a connection between the entity and the database. Now, go to Solution Explorer and migration folder and open the configuration.cs file.

namespace Employee.Migrations
{
    using Employee.Models;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<Employee.Models.ApplicationDbContext>
    {
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(Employee.Models.ApplicationContext 
         context)
      {
        var emp = List<Employee>
     {new Employee() { Name="John", Age="Doe" , ContactNo="02135648978", Email="john@example.com"},
			  new Employee() { Name="Marry", Age="Moe" , ContactNo="02135644569", Email="mary@example.com"},
			  new Employee() { Name="July", Age="Dooley" , ContactNo="0213564870864", Email="july@example.com"},
			}
            emp.ForEach(e=>context.Employees.AddOrUpdate(p=>p.Id,e));
            context.SaveChanges();
        }
    }
}

Inside the sealing method, we add some dummy data. Because, whenever you create a first-time data. so you need to some dummy data to insert on the database.

So, here we create a three-employee dummy data and now this employee is at a trade for each time. so one by one employee data adds or update.

Now, go to the record manager console and add a migration and use the migration name and then update the database. you can see the following command.

add a migration on database

Now, go to Solution Explore > data connection DefaultConnectionEmployee. and here, you can see the Employee table.

databasr migration table

Creating our Controller

here, we are creating our “EmployeeController” and achieve the “scaffold” option. and then right click on the “Controllers” folder. and then select “ MVC controller with views, using Entity Framework”.

MVC controller with views, using Entity Framework

This controller will automatically create perform CRUD operation. so, we don’t write to code. then add model class and Data context class.

Data context class.

Now, in our EmployeeController file, now yes can see, It creates a CRUD operation. and write code for us.

using System;
using System.Linq;
using System.Web.Mvc;
using System.Data.Entity;
using System.Net;
using Employee.Model;

namespace Employee.Controllers
{

    public class EmployeesController : Controller
    {
	    private ApplicationDbContext db =  new ApplicationDbContext();
       
        public ActionResult Index()
        {
            return View(db.Employees.ToList());
        }

        public ActionResult Details(int? id)
        {
		    Employee employee = db.Employees.Find(id);
		    return View(employee);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Email,ContactNo"] Employee employee)
        {
            if (!ModelState.IsValid)
            {
			    db.Employee(employee).State = EntityState.Modified;
				db.SaveChanges();
		    	return View("Index");
            }
		}

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Email,ContactNo"] Employee employee)
        {
            if (!ModelState.IsValid)
            {
     			db.Employee.Add(employee);
				db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        public ActionResult Delete(int? id)
        {
            Employee employee = db.Employee.Find(id);
            return View(employee);
        }
		
		protected override void Dispose(bool Disposing)
        {
		  if(Disposing)
		  {
		    db.Dispose();
		  }
		  base.Dispose(Disposing);
		}
	}   
}

Now, we built the project and will succeed. then go start without debugging. and you can see the following output.

asp.net mvc output

all the data, we served it on the seed method to the dummy data. so, here we create new employee form

create asp.net mvc form

Deploy application on Azure

Now, our application is complete and ready for deployment and hosting on Azure. Let’s, open your browser and go to the https://portal.azure.com. if your new user. then, Create New account or log in.

Now, after the login. you can see the welcome Azure portal.

 Azure portal

so, let’s go this path and click on (“New >> Web+Mobile >> Web App“). after that and here you can see here open a new form.

azure webapps
create webapps profile

And Let’s, fill all information required. Add App name, subscription, Resource group, app service plan, and application insights. then click on the create button.

Now, our website creates on the Azure server. so, here URL of our website

website creates on the Azure server

Add Sql database

Now, we create a SQL database. so, go to the SQL category and Add a new SQL database

create a SQL database

It will let you create a new SQL database and new server, then we can specify the endpoint, then add the required field for the new server.

so, you can see the dashboard, SQL database creates on Microsoft Azure service.

SQL database creates on Microsoft Azure service

Now, we go to our application and then right click on our project and click on the publish. so, there is a three type of method. you can publish your website

import project for publish

here, we need to download the public profile from Azure. then go to our website and click on more option, then select the get public profile.

 download the public profile from Azure

After that, browse profile in import method. then here you can see, there are many settings of your website. now you can see, it will load the data in the field.

Next step, click on validate connection button and check success or not. click on the next. we will check now you can clean application daily contacts is remote connections with long you enter your world collection.

select database remotely connection on azure

so, the connection string is defined in the Microsoft Azure created the database.

connection string is defined in the Microsoft Azure created database

then, copy that connection string and paste into database connection settings.

verify connection string

The final step is to click on the publish button now, our website going to publish.

publish library files on azure

After this now we open our website. and perform CRUD operations on employees.

perform CRUD operations

in index page, asp.net mvc hosted application on azure. so, now our application successfully deployed

Thanks for the Reading article! I hope this get’s you started application using ASP.NET Core using Microsoft Azure. Take care.

Leave a Reply

Your email address will not be published. Required fields are marked *