ASP. NET Core is the latest open-sourced and cloud-optimized web framework developed by Microsoft to build web applications. It is a framework that runs on the full .NET Framework, on Windows, and the cross-platform .NET. The ASP.NET Core replaced the original .NET framework. It was redesigned from the base to be more flexible, fast, and modern to support different platforms smoothly. 

ASP.NET was in vogue for a long time to develop and deploy applications to the web. But with an increase in the number of platforms and with developing technology, the need for a more advanced and modern web framework was inevitable. Although there might be some basic functionalities that are the same as ASP.NET, ASP.NET Core is an entirely new framework and differs a lot.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

What Is ASP.NET Core?

  • ASP.NET Core was first released in 2016 as a revamped version of earlier Windows-only ASP.NET versions.
  • ASP.NET Core is a high-performance, cross-platform framework for building modern, cloud-enabled Internet-connected applications.
  • ASP.NET Core is an open-source ASP.NET version that runs on Windows, Mac OS X, and Linux.

Project Layout

In this section, we will discuss the file system and how the files and directories work in conjunction. The image below shows the homepage of a new project created in ASP.NET Core.

ASP.NET_Core_1

The section on the right shows the files and directories created by default after creating a new project in ASP.NET Core. 

In the Solution Explorer window, there is a file named global.json which tells the ASP.NET where to look for the application source code. The file looks like this:

ASP.NET_Core_2

If your source code is not present in either of the folders, test, and src, your code won’t be available for build. You can change the settings wherever you need to. 

ASP.NET Core compiles your application after any modification, or addition, or deletion of files. This differs from ASP.NET that had a project file named *.cs proj which contained a manifest of everything present in the application folder.

Project.json

The project.json is a javascript file that uses object notation to store configuration info, dependencies, and package names. It is one of the most important files in the entire project. It is essential to build an ASP.NET application. The file appears as shown below:

ASP.NET_Core_3.

The initial lines contain dependencies and tools to support the languages and frameworks used by ASP.NET Core to build a working application. You can also install packages and dependencies if you need to.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Configuration

The Startup.cs file in the project directory consists of all the configuration settings. It contains two functions by default. The first one is ConfigureServices. It is used to add services to the container and is called in the runtime. The second method is Configure that is used to configure the HTTP request pipeline.

The default code for Startup.cs is:

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.Logging;  

namespace FirstAppDemo { 

   public class Startup { 

      // You can add this method to add services to the container. 

      public void ConfigureServices(IServiceCollection services) { 

      }       

      // You can add this method to configure the HTTP request pipeline.

      public void Configure(IApplicationBuilder app, IHostingEnvironment env, 

         ILoggerFactory loggerFactory) { 

         loggerFactory.AddConsole();           

         if (env.IsDevelopment()) { 

            app.UseDeveloperExceptionPage(); 

         }  

         app.Run(async (context) => { 

            await context.Response.WriteAsync("Hello World!"); 

         }); 

      } 

   } 

}

Middleware

Middleware are software components in an application used to handle requests and responses. It also controls the error responses and plays an important role in user authentication and authorization.  

Every part of Middleware is an object and is used for specific purposes. We need pieces of Middleware to make the application interface correct and smooth. It is also referred to as a series of components used in the processing pipeline to help in the authorization of users.

Exceptions

Exceptions and errors are handled in a variety of ways in an ASP.NET Core app. As mentioned above, Middleware helps to identify, process, and respond to errors and exceptions through a diagnostics package.

Example

Let’s simulate an error with a piece of code and handle it accordingly. 

Code

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; }         

      // You can add this method to add services to the container. 

      public void ConfigureServices(IServiceCollection services) { 

      }        

      // You can add this method to configure the HTTP request pipeline.

      public void Configure(IApplicationBuilder app) { 

         app.UseIISPlatformHandler();  

         app.UseRuntimeInfoPage();           

         app.Run(async (context) => { 

            throw new System.Exception("Throw Exception"); 

            var msg = Configuration["message"]; 

            await context.Response.WriteAsync(msg); 

         });  

      }          

      // Entry point for the application. 

      public static void Main(string[] args) => WebApplication.Run<Startup>(args); 

   }   

Output: 

ASP.NET_Core_4

The above code produces an error. But it is quite generic and does elaborate on the problem. It would be nice to have something more self-explanatory. Now we add another piece of code to receive a more detailed message on the problem. 

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Code:

public void Configure(IApplicationBuilder app) { 

   app.UseIISPlatformHandler();  

   app.UseDeveloperExceptionPage(); 

   app.UseRuntimeInfoPage();  

   app.Run(async (context) => { 

      throw new System.Exception("Throw Exception"); 

      var msg = Configuration["message"]; 

      await context.Response.WriteAsync(msg); 

   });  

}

Output:

ASP.NET_Core_5

As you can see, the error message that appeared this time is quite detailed. It says that there was an unhandled exception at line 37 of Startup.cs.

What Are Static Files?

The static files are the CSS files, images, and Javascript files present in the file system which is served directly to the client. They are located in the root web folder (wwwroot). It is the only place to serve files from the file system by default. Anything that you keep inside this folder is servable.

How to Set Up MVC?

To set up the MVC Framework in an empty project, follow these steps.

Step 1: Install the package Microsoft.AspNet.Mvc.

Step 2: After successful installation, register all the services that MVC requires at runtime inside the ConfigureServices method.

Step 3:  Finally, install the middleware necessary for the ASP.NET MVC to receive requests.

MVC Design Pattern

The MVC or Model-View-Controller has been around for a few decades now and is very popular with all the latest technologies used to build User Interfaces. Everything from Smalltalk to C++ to Java to C# and now .NET uses the MVC Design Pattern as a design pattern to build User Interfaces. MVC divides the UI into three parts, i.e., the Model, the View, and the Controller where the Model is a set of classes that describes the data and the business logic; the View defines the UI’s look and appearance, and the Controller handles the application logic, and it’s work-flow.

What Is Routing in ASP.NET?

In ASP.NET, routing is the process of directing the HTTP requests to the right controller. The MVC middleware must decide whether a request should go to the controller for processing or not. The middleware makes this decision based on the URL and some configuration information. This is known as convention-based routing. Here is a code snippet for convention-based routing.

Code:

routeBuilder.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}"); 

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

What Are Attribute Routes?

Attribute-based Routing is an alternative to convention-based routing. We use C# attributes in the controller classes and the methods internally in this type of routing. The Attribute-based Routing method specifies metadata that tells ASP.NET Core when to call a method. The routes are evaluated in the order of their appearance or in the order in which they are registered.

What Are Action Results?

Instead of using C# classes as controllers, we can derive controllers from Microsoft.AspNet.Mvc namespace. The base class gives us access to some info about the requests and the methods that help us to build results for those requests. These results are encapsulated into an object that implements the IActionResult interface. There are a lot of action results, some of which are listed below along with their behaviors.

ContentResult

Returns a string

FileContentResult

Returns file content

FilePathResult

Returns file content

FileStreamResult

Returns file content.

EmptyResult

Returns nothing

JavaScriptResult

Returns script for execution

JsonResult

Returns JSON formatted data

What Are Views in ASP.NET Core?

In an ASP.NET Core MVC application, there is no concept of a webpage i.e everything that you see is a view. In such applications, the response to a request is a view or the controller might redirect the request to another controller action. One of the most popular methods for creating HTML in the MVC Framework is to use the Razor View Engine in ASP.NET MVC.

DBContext

DBContext is the primary class, responsible for interacting with data as objects. To work with DBContext, you must define a class that derives from the DBContext and exposes the DBSet properties representing the specified entities in the context. It maps to a database with a schema that it understands. It acts as a bridge between entity classes and the database.

Full Stack Java Developer Course

In Partnership with HIRIST and HackerEarthEXPLORE COURSE
Full Stack Java Developer Course

What Is Razor?

Razor is a markup syntax that uses server-based code embedded into web pages. It is based on ASP.NET and is used for creating web applications. Although it is based on the traditional ASP.NET, it is easier to use and easier to learn. Razor supports both Visual Basic and C# and is similar to HTML. 

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

There is a lot more to the ASP.NET Core web framework such as routing, MVC setup and design patterns, DB context, Razor, etc. If you wish to learn Web Development in detail, Simplilearn provides an excellent course on Full Stack Web Development, which not only covers fundamentals but will also train you on an industry level which will help you in landing better job prospects at Web Dev.

If you have interests other than just Full Stack Web Dev, Simplilearn also provides courses on a variety of technologies to upscale your career such as Java, Python, Blockchain, Javascript, SQL, ReactJS, and so on. If this interests you, check out Simplilearn's skill-up courses here.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
  • *According to Simplilearn survey conducted and subject to terms & conditions with Ernst & Young LLP (EY) as Process Advisors