Top 20 ASP.NET core interview questions

Facebook
Twitter
LinkedIn

Never miss a post!

Sign up for our newsletter and get FREE Development Trends delivered directly to your inbox.

You can unsubscribe any time. Terms & Conditions.
Categories

Let us guide you through the top 20 ASP.NET Core interview questions. Whether you are the interviewer or the candidate, these questions will help you get a better understanding of what is important to know for your interview, provide you with a good revision and improve your technical skills.

What is ASP.NET Core?

ASP.NET is a complete redesign of ASP.NET using .NET Core Framework. It is open-source and cross-platform (can run on macOS, Linux and Windows). ASP.NET Core runs faster than ASP.NET. It is also easily configurable, modular, scalable, and extensible. It is able to work with both .NET Core and .NET Framework using the .NET Standard framework. ASP.NET Core is used by web developers looking to develop a cloud-based web/mobile or IoT application.

What is .NET Core?

.NET Core is a successor to .NET Framework. In contrast to the .NET Framework, .NET Core is an open-source cross-platform that allows you to develop applications in different operating systems.

Cross-Platform: It supports Windows, MAC OS and Linux and also on mobile devices such as Android and iOS.

Flexible deployment: It is included in your application or deployed side-by-side with your application.

Compatible: It is compatible with .NET Framework, Mono and Xamarin.

Modular: .NET Core is released by NuGet in small package assemblies. .NET Framework is released as one large assembly with the core functionalities. This modular approach allows developers to build a smaller app which decreases security risks, increases performance and decreases costs.

What functionalities are supported by ASP.NET Core?

  • Built-in support for dependency injection
  • Built-in support for an extensible logging framework
  • Contains Kestrel – a cross-platform web server that allows web applications to execute without the need for IIS, Apache or Nginx.
  • Functionality to use multiple hosts
  • Supports modularity – the developer must include the module that is required by the application.
  • Makes use of an app JSON file to store settings instead of a web.config
  • Contains a startup class to initiate and run services (Instead of global. asax)
  • Has extensive support for asynchronous programming

What is ASP.NET Core Middleware?

ASP.NET Core Middleware is a group of small modules that are incorporated into an HTTP request pipeline. Middleware is used to implement several tasks when handling requests. Such examples include authentication, session state retrieval and persistence, logging and much more. It gives you control on the order of when the requests should be executed, unlike ASP.NET Core HTTP modules.

Middleware is configured by code rather than web.config in ASP.NET. It is found inside your Startup.cs file:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
{ 
     if (env.IsDevelopment()) 
         app.UseDeveloperExceptionPage(); 
     app.UseHttpsRedirection(); 
     app.UseExceptionHandler(); 
     app.UseRouting(); 
     app.UseAuthorization(); 
     app.UseEndpoints(endpoints => 
     { 
          endpoints.MapControllers(); 
     }); 
     app.UseStaticFiles(); 
}

The configure method as seen above is used to create a request pipeline via middlewares. The method applies the following functionality:

  • Adds error pages and error handlers
  • Adds HTTPS Redirection
  • Adds support for static files
  • Makes use of ASP.NET Identity authentication
  • Adds routing and endpoint using map controllers

What is the difference between ASP.NET and ASP.NET Core?

ASP.NET Core is a total rewrite of ASP.NET. It is an open-source cross-platform that allows you to build web applications in Windows, Mac and Linux. It is also capable of working with both .NET Core and .NET Framework.

Here are the main differences:

  • Project configuration – ASP.NET Core does not make use of web.config. Instead, appsettings.json or other custom configuration files are used. A new folder named wwwroot is also added to the project structure. This is the container for all static files which are sent to the browser such as CSS, HTML, JavaScript and image files.
  • Not dependent on IIS – It is not IIS dependent like ASP.NET and allows you to host on IIS, Docker, Nginx, Kestral and Apache.
    Installation – since its cross-platform, frameworks are prepackaged and compiled via NuGet.
  • Microservices – Microservices were simplified in .NET Core. Programmers can develop custom microservices and combine them to build powerful systems seamlessly.

What is Kestral?

Kestrel is a web server build for ASP.NET core which is cross-platform

  • It is based on libuv – a cross-platform asynchronous I/O library
  • It is the default web server for all ASP.NET Core templates.
  • It is fast and secure and can even be used without a reverse proxy server. However, it is still recommended to use with IIS, Nginx or Apache.

What are Razor Pages in ASP.NET Core?

As of ASP.NET Core 2.1, Razor pages were introduced. It follows a page-development model like in ASP.NET web forms.
Razor pages start with a @page directive. This means that it handles requests directly without the need to go through the controller.

Here is an example of the page and model directive in the CSHTML file and its associated page model class (CSHTML.CS)

@page 
@model AboutModel 
<div> 
      The current time is @Model.CurrentTime.ToShortTimeString() 
</div> 

--About.cshtml.cs--- 
using System; 
using Microsoft.AspNetCore.Mvc.RazorPages; 

public class AboutModelModel : PageModel 
{ 
       public DateTime CurrentTime = DateTime.UtcNow; 
}

When comparing with the classic Home Controller example in ASP.NET MVC, the equivalent of razor pages would be Index (Home), About, Contact and Error pages all in the root directory.
For example in each page, you will find the HTML page (cshtml) and its page model class page (cshtml.cs). This is in contrast with MVC approach where controllers, view models and view models all had different locations in entirely different folders.

Can ASP.NET Core work with .NET Framework?

Yes. ASP.NET Core can work with .NET framework using the .NET standard library.

What’s the difference between .NET Core .NET Framework and .NET Standard?

.NET Standard is a specification for implementing the Base Class Library (BCL). BCL contains classes such as exception handling, XML, collections, I/O and networking. WPF, WCF and ASP.NET do not form part of BCL and so are not included in .NET Standard library.

  • NET Core is a managed framework that builds desktop and web applications in cross-platform.
  • .NET Framework is a framework that builds desktop and web applications in Windows only. It is highly dependent on the architecture.
  • Both “.NET Core” and “.NET Framework” include .NET Standard for BCL in their managed framework.

What is routing in ASP.NET Core?

In ASP.NET Core, routing is the process of mapping incoming requests to the route handler. The route can have arguments inside the URL which are then used to process the call. Routing works by finding the route handler based on the URL given. There are two types of routing in ASP.NET Core.

Attribute – used in REST APIs
Conventional – used with controllers and views in MVC architecture

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

Above is an example to map both conventionally routed controllers and attribute controllers.

How do you enable a session in ASP.NET Core?

The package Microsoft.AspNetCore.Session provides the middleware for the session. To make use of this session in an ASP.NET Core application, you need to include this package in its csproj file. The Session middleware must then be added in the Startup file in the ASP.NET Core request pipeline.

public class Startup
{
   public void ConfigureServices(IServiceCollection services)
   {
     ...
     services.AddSession();
     services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       ...
       app.UseSession();
    }
}

Advantages of ASP.NET Core over ASP.NET

Here are a number of reasons why ASP.NET Core is better than ASP.NET:

  1. It is cross platform (Windows/Linux/Mac/Android/iOS)
  2. There exists no dependencies in the framework installation because the packages that are required are directly integrated with application
  3. It handle a higher number of requests than ASP.NET
  4. ASP.NET Core offers numerous deployment options.

What is WebListener?

WebListener is a web server in ASP.NET Core that runs only on Windows host machines. It is an alternative to Kestrel and is built on HttpSys kernel-mode driver. Also, is used for direct connection to the internet without the need of an IIS as a reverse proxy server. It is not compatible with IIS.

What is IWebHostEnvironment interface used for?

IWebHostEnvironment is an interface for .NET Core. It is used to get information on the web hosting environment an application is executing in. It needs to be injected as a dependency on the controller. The interface has two properties:

  • WebRootPath – Path of the WWW folder
  • ContentRootPath – Path of the root folder which includes all the application files.

What are the Service lifetimes?

Service lifetimes define the conditions in which a new service instance will be instantiated. Here are the three types of service lifetimes defines by the .NET Core DI framework:

Transient – Instance is created every time they are requested.
Scoped – Per every web request or any unit of work. We call this a scope.
Singleton – Created only for the first request. If the singleton instance is specified at registration time, the instance will be available to all consumers of the registration type.

//Transient 
services.AddTransient<ILifeServiceExample, LifeServiceExample>(); 
//Scoped 
services.AddScoped<ILifeServiceExample, LifeServiceExample>(); 
//Singleton 
services.AddSingleton<ILifeServiceExample, LifeServiceExample();

What is wwwroot folder in ASP.NET Core?

By default. the wwwroot is the root folder that contains the static files such as HTML, CSS and Javascript.

The files can be stored here and accessed with a relative path to the root. Only these files inside the wwwroot can be served over HTTP Requests. All other files are filtered out and cannot be served by default.

The files can be accessed in this format:

http://domain:<port>/html/app.html

To set this up you need to add a middleware for serving static files in the Configure method of your Startup.cs.

What is the difference between UseIIS & UseIISIntegration?

Before ASP.NET Core 2.2, ASP.NET Core was hosted outside of the IIS process. This meant that we had two processes for ASP.NET core application:

w3wp.exe – the IIS Process
dotnet.exe – the ASP.NET Core process. This is where Kestrel web server was started.

IIS and Kestrel communicated between these two mentioned processes. In this case, you need to use UseIISIntegration.

However, in later versions, ASP.NET Core introduced in-process hosting. ASP.NET Core no longer ran separately but runs inside IIS w3wp.exe process. This removes the need for the Kestrel web server. For this case, you would need to specify UseIIS.

What is Dependency Injection and how is it implemented in ASP.NET Core?

A dependency is any object that is required from another object. Here is an example of a dependency:

public class DependencyClass 
{ 
   public DependencyClass() { } 
   public Task SayHello(string name) 
   { 
        Console.WriteLine($"Hello to you, {name}"); return Task.FromResult(0); 
   } 
}

Now, an instance can be created from DependencyClass to get access to ‘SayHello’ method. DependencyClass now becomes a dependency of the AboutModel. See example below:

public class AboutModel : PageModel 
{ 
    DependencyClass _dependencyClass = new DependencyClass(); 
    public async Task IntroduceAsync() 
    { 
        await _dependencyClass.SayHello("AboutModel.IntroduceAsync created this message"); 
    } 
}

This creates a problem because code dependencies (as above example) are problematic and it is recommended not to use where possible. Reasons for this are the following:

In order to replace DependencyClass with a different implementation, the class itself must be modified.
If DependencyClass has dependencies, they must be set up by the class. With large projects containing multiple classes depending on DependencyClass, this will be cumbersome.
It will be hard to unit test. DependencyClass cannot be mocked or stubbed in this case.

This is where Dependency injection comes in. This is how it addresses these problems in ASP.NET Core:

Interface or base class as an abstraction for the dependency implementation (IDependencyClass)

The dependency must be registered as a service inside a service container. ASP.NET Core contains a built-in service container, IServiceProvider. Services are registered in the app’s Startup configure method.

The service is then injected into the constructor in the class it’s used in. The framework takes care of instantiating the dependent and disposing of it.

The above technique is called Inversion of Control (IoC) between classes and their dependencies. For more information and samples how to do this, see here.

What are technologies discontinued in .NET Core?

he following technologies have been discontinued in .NET Core:

  • Reflection – Has been converted into a lightweight version. An extension method called GetTypeInfo exposes information that you normally retrieve from Type object. However, it is not as detailed as the original.
  • AppDomain – AppDomains isolate apps from each other. They require runtime support and are costly. Creating more app domains is unsupported and there aren’t any plans to add this in the future. Microsoft recommends using separate processes or containers as an alternative.
  • Remoting – .NET Remoting created several issues in its architectural design. Since it’s used for cross-AppDomain, which is no longer supported, it was decided to not support it either. It also cost them a lot due to runtime support.
  • Security Transparency – Due to security reasons, Security transparency is no longer supported. It used to separate sandbox code from security-critical code in a declarative method. Microsoft recommends you use security boundaries provided by the operating system itself. Such examples include virtualization, contained or user accounts.

What does Configure Services method do in the startup class?

ConfigureServices method takes care of registering services which are consumed across the application using Dependency Injection (DI) or Application Services.

public void ConfigureServices(IServiceCollection services) 
{ 
     services.AddEntityFramework()
        .AddSqlServer()
     .AddDbContext<MusicContext>()
     .AddControllersWithViews().AddRazorPages(); 
}

What is a Self-hosted Web Application?

SP.NET Core is fully decoupled from the web server environment hosting the application. It still supports IIS and IIS Express but by default, it uses self-hosting scenarios by using Kestrel and WebListener HTTP Servers.

Here is a sample of how to configure a web application that is self-host:

public class Program 
{ 
     public static void Main(string[] args) 
     { 
         var config = new ConfigurationBuilder()
                      .AddCommandLine(args)
                      .AddEnvironmentVariables(prefix: "ASPNETCORE_").Build(); 

         var host = new WebHostBuilder()
                          .UseConfiguration(config)
                          .UseKestrel()
                          .UseContentRoot(Directory.GetCurrentDirectory())
                          .UseStartup<Startup>().Build(); 
         host.Run(); 
     } 
}

What is a .NET Generic Host?

As of ASP.NET Core 3, they exported ASP.NET code to run on a .NET Generic Host instead of the previously used WebHost. .NET Generic Host is a non-web version of the WebHost that runs on ASP.NET Core. It is an abstraction layer for both Web and non-web functionality.

They decoupled HTTP pipeline from the Web Host API to enable a wider collection of host environments. For example, non-HTTP workloads that used to be in Web Host API were background tasks, messaging, dependency injection (DI), logging and more. Now they have been separated completely using the Generic host. With this abstraction, developers are able to use these mechanisms for console applications, systemmds, windows services, and web applications.

How to configure Logging in ASP.NET Core

ASP.NET Core supports a logging API that works with multiple built-in and third-party logging providers. To set up logging in ASP. NET Core you need to apply the following;

public static IHostBuilder CreateHostBuilder(string[] args) 
{ 
        Host.CreateDefaultBuilder(args).ConfigureLogging(logging => 
        { 
             logging.ClearProviders(); 
             logging.AddConsole(); 
             logging.AddDebug(); 
             logging.AddTraceSource("Information"); 
        }).ConfigureWebHostDefaults(webBuilder => 
                                   { 
                                       webBuilder.UseStartup<Startup>(); 
                                   }); 
}

In the above example, the ConfigureLogging() method takes action to delegate Action<ILoggingBuilder> to configure logging providers. To add custom logging providers, start off by removing all default providers. To do this call ClearProviders(). In our example, we add the Trace Souce and Debug providers instead. We also add the Console logging provider to add logs to console too.

What is the difference between Pages and Views ?

Pages is a new page framework that was introduced in .NET core 2.0. Pages is an evolution of the old WebFroms and provides an easier way to generate pages as opposed to asp.net MVC.

The Razor Page is very similar in concept to the standard Model View Controller framework. In main difference is that the Model and the controller are included inside the page. Razor Pages provide a simpler development approach when compared to the standard MVC framework.

 

Facebook
Twitter
LinkedIn

Our website uses cookies that help it to function, allow us to analyze how you interact with it, and help us to improve its performance. By using our website you agree by our Terms and Conditions and Privacy Policy.