Skip to main content

ASP.NET Core - MVC Setup

Here we will set up the MVC framework in our FirstAppDemo application. We will proceed by building a web application on top of the ASP.NET Core, and more specifically, the ASP.NET Core MVC framework. We can technically build an entire application using only middleware, but ASP.NET Core MVC gives us the features that we can use to easily create HTML pages and HTTP-based APIs.
To setup MVC framework in our empty project, follow these steps −
  • Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework.
  • Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the ConfigureServices method.
  • Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write.
Step 1 − Let us go to the NuGet package manager by right-clicking on the Manage NuGet Packages. Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework.
Microsoft.AspNet.MVC
Step 2 − Once the Microsoft.AspNet.Mvc package is installed, we need to register all the services that ASP.NET Core MVC requires at runtime. We will do this with the ConfigureServices method. We will also add a simple controller and we will see some output from that controller.
Let us add a new folder to this project and call it Controllers. In this folder, we can place multiple controllers as shown below in the Solution Explorer.
Controllers
Now right-click on the Controllers folder and select on the Add → Class menu option.
Add Class
Step 3 − Here we want to add a simple C# class, and call this class HomeController and then Click on the Add button as in the above screenshot.
Home Controller
This will be our default page.
Step 4 − Let us define a single public method that returns a string and call that method Index as shown in the following program.
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks;  

namespace FirstAppdemo.Controllers { 
   public class HomeController { 
      public string Index() { 
         return "Hello, World! this message is from Home Controller..."; 
      } 
   } 
}
Step 5 − When you go to the root of the website, you want to see the controller response. As of now, we will be serving our index.html file.
Controller Response
Let us go into the root of the website and delete index.html. We want the controller to respond instead of index.html file.
Step 6 − Now go to the Configure method in the Startup class and add the UseMvcWithDefaultRoute piece of middleware.
UseMvc Default Route
Step 7 − Now refresh the application at the root of the website.
Refresh the Application
You will encounter a 500 error. The error says that the framework was unable to find the required ASP.NET Core MVC services.
The ASP.NET Core Framework itself is made up of different small components that have very focused responsibilities.
For example, there is a component that has to locate and instantiate the controller.
That component needs to be in the service collection for ASP.NET Core MVC to function correctly.
Step 8 − In addition to adding the NuGet package and the middleware, we also need to add the AddMvc service in the ConfigureServices. Here is the complete implementation of the Startup class.
using Microsoft.AspNet.Builder; 
using Microsoft.AspNet.Hosting; 
using Microsoft.AspNet.Http; 

using Microsoft.Extensions.DependencyInjection; 
using Microsoft.Extensions.Configuration;  

namespace FirstAppDemo { 
   public class Startup { 
      public Startup() { 
         var builder = new ConfigurationBuilder() .AddJsonFile("AppSettings.json"); 
         Configuration = builder.Build(); 
      }  
      public IConfiguration Configuration { get; set; }
      
      // This method gets called by the runtime. 
      // Use this method to add services to the container. 
      // For more information on how to configure your application, 
      // visit http://go.microsoft.com/fwlink/?LinkID=398940 
      public void ConfigureServices(IServiceCollection services) { 
         services.AddMvc(); 
      }
      
      // This method gets called by the runtime.  
      // Use this method to configure the HTTP request pipeline. 
      public void Configure(IApplicationBuilder app) { 
         app.UseIISPlatformHandler();  
         
         app.UseDeveloperExceptionPage(); 
         app.UseRuntimeInfoPage();  
         
         app.UseFileServer(); 
         app.UseMvcWithDefaultRoute();  
         
         app.Run(async (context) => { 
            var msg = Configuration["message"]; 
            await context.Response.WriteAsync(msg); 
         });
      } 
      
      // Entry point for the application. 
      public static void Main(string[] args) => WebApplication.Run<Startup>(args); 
   }  
}            
Step 9 − Save the Startup.cs file and go to the browser and refresh it. You will now receive a response from our home controller.
Startup.Cs HomeController

Comments

Popular posts from this blog

ASP.NET Core - Create New Project

You can start building a new ASP.NET Core Application from the  File → New Project  menu option. On the New Project dialog box, you will see the following three different templates for Web projects − ASP.NET Web Application  − The simple ASP.NET application templates . ASP.NET Core Web Application (.NET Core)  − This will start you with a crossplatform compatible project that runs on the .NET Core framework. ASP.NET Core Web Application (.NET Framework)  − This starts a new project that runs on the standard .NET Framework on Windows. In the left pane, select  Templates → Visual C# → Web  and in the middle pane select the ASP.NET Core Web Application (.NET Core) template. Let us call this application  FirstAppDemo  and also specify the Location for your ASP.NET Core project and then Click OK. In the above dialog box, you can select a specific template for the ASP.NET application from the available ASP.NET Core Templates. ...

ASP.NET Core - Attribute Routes

Learn another approach to routing and that is attribute-based routing. With attribute-based routing, we can use C# attributes on our controller classes and on the methods internally in these classes. These attributes have metadata that tell ASP.NET Core when to call a specific controller. It is an alternative to convention-based routing. Routes are evaluated in the order that they appear, the order that you register them in, but it's quite common to map multiple routes particularly if you want to have different parameters in the URL or if you want to have different literals in the URL. Example Let us take a simple example. Open the  FirstAppDemo  project and run the application in the browser. When you specify  /about , it will produce the following output − What we want here is that when we specify  /about , the application should invoke the Phone action of the AboutController. Here, we can enforce some explicit routes for this controller using a Ro...

Features of Node.js

Following are some of the important features that make Node.js the first choice of software architects. Asynchronous and Event Driven  − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Very Fast  − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable  − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than t...