Skip to main content

ASP.Net Core MVC Project Part 2

Configuration and Routing

In this article we will configure services. This article is second part of Asp.Net Core MVC project series. Please read article ASP.Net Core MVC Project Part 1 before reading this article.In previous article we had created Asp.Net Core empty project and now changes will be done in that project.
Now we will add services in Startup.cs class which application will need. ASP.Net Core 3.1 is designed to be very lightweight so everything which we need, we have to add it explicitly. Since we are creating ASP.Net Core MVC project so we need to add support for MVC explicitly.
For adding MVC support ,we need to change ConfigureServices() method in Startup.cs file.
Method AddControllersWithViews() adds support for MVC:

public void ConfigureServices(IServiceCollection services)
{
 services.AddControllersWithViews();
}

Above statement enables us to use Controllers , Models and Views.

Startup.cs

public class Startup
{
	// This method gets called by the runtime. 
	public void ConfigureServices(IServiceCollection services)
	{
         services.AddControllersWithViews();
	}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
	if (env.IsDevelopment())
	{
		app.UseDeveloperExceptionPage();
	}

	app.UseRouting();

	app.UseEndpoints(endpoints =>
	{
	endpoints.MapGet("/", async context =>
	{
	 await context.Response.WriteAsync("Hello World!");
	});
     });
   }
}

Now see Configure() Method in Startup.cs class , please see above code snippet. This method takes IWebHostEnvironment type as input parameter.It will tell the environment in which application should run.
By default application will run in Development environment which is already setup. Method UseDeveloperExceptionPage() displays exceptions encountered during development.We should disable this before deployment of application in Production.

To see the environment , Right click on Project and select Properties and click on Debug tab. Below screenshot shows Environment variable.

You should change this value manually before deployment in production.

Second parameter in Configure() method is of type IApplicationBuilder.This parameter is used to add middleware. So lets add one middleware for HTTPS. We want to use HTTPS so we need to tell the application that we want to redirect pages to HTTPS. Below is the code for HTTPS support:

app.UseHttpsRedirection();

We need to place this before routing configuration. Below is the complete code of Configure method after adding HTTPS middleware:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
	if (env.IsDevelopment())
	{
	 app.UseDeveloperExceptionPage();
	}
	app.UseHttpsRedirection();
	app.UseRouting();

	app.UseEndpoints(endpoints =>
	{
	  endpoints.MapGet("/", async context =>
	  {
	   await context.Response.WriteAsync("Hello World!");
	   });
	});
}

ASP.Net Core request pipeline can have multiple middlewares and request will passed through each middleware.

Next we need to enable support of static files such as images, javascript and css etc. For this we have to use method UseStaticFiles():

 app.UseHttpsRedirection();
 app.UseStaticFiles();
 app.UseRouting();

This method will search automatically for folder “wwwwroot” and it will search for all static files in this folder.

In Configure() method, UseRouting() and UseEndpoints() were automatically added when project was created.These 2 methods enables MVC to respond to requests.We need EndPoints for controller routing, so request will go through a Controller and its action and it will be part of URL.
So now we will change code which displays “Hello World” and we will add MVC default routing pattern:
Below code is removed from Configure() method:

endpoints.MapGet("/", async context =>
{
 await context.Response.WriteAsync("Hello World!");
});

Below is the code for adding default routing pattern:

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
	name:"default",
	pattern:"{controller=Home}/{action=Index}/{id?}"
	);
});

Above is the code for adding default routing pattern. According to this default routing pattern, after domain name there should be controller name and after that action should be there. If no controller is specified then default controller will be Home controller and default action will be Index action.Here parameter name is id and it will be placed after action name in URL. Parameter id is optional so URL may not contain any parameter.

We can add more specific routes as per our requirement but this will be default routing pattern. It enables to route incoming request through controller and its action.

Below is the complete Startup.cs class

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace eShop
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}

	
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
 app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
	name:"default",
	pattern:"{controller=Home}/{action=Index}/{id?}"
	);
   });
  }
 }
}

There is no controller yet in our project so lets create our first controller. Create a folder named “Controllers”.
Right click on Project and select Add and then New Folder.

Give name “Controllers” to the folder.
Now right click on Controllers folder and add new controller.

Give name “HomeController”. Controller word should be suffixed after Home word. Below is generated Home Controller class, it is inherited from “Controller” class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace eShop.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
 return View();
  }
 }
}

So we have our controller and it has Index action. Now we need to add Index view corresponding to Index action.

Right click on Index action and select “Add View”:

A folder named “Home” will be created inside Views folder.Name “Home” is corresponding to controller name.For each controller if we add a view for any action then a folder similar to controller name will be created and a view with action name will be created inside folder.

Below is the code of View:

Index.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h1>Welcome to eShop Project</h1>
</body>
</html>

I have added <h1> tag in Index view for displaying text on browser :

Welcome to eShop Project

Now we have controller, action and its view created, now lets test our application. Press F5 in visual studio and below is the output:

You can see that output of Index action is displayed on browser but URL does not contain controller name and action name. According to our default route pattern which we have added in Configure() method of Startup.cs file, default controller will be Home and default action will be Index if controller and action are not present in URL.

In this article we have seen customization of Configure() method to add multiple middlewares and adding default routing pattern.We have also seen steps for creating Controller and action.

Download code from below URL:
https://github.com/vijendra-ksh/eShop

Leave a Reply

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