ASP.Net Core interview Questions and Answers

In this article, I have collected important ASP.Net Core interview questions and the answers, which will help you in preparing your interview. If you are an ASP.Net or ASP.Net Core programmer or developer who is preparing for an interview, then believe that you are reading the right blog.

.Net Core interview questions given below will prove to be very beneficial for freshers and experienced developer both. So, without delay, let’s read each interview question of ASP.Net Core and its answer because below are some essential and frequently asked interview questions and answers.

Below given interview questions applied to .Net Core 2.1, .Net Core 3.1 and .Net 5 as well. All the .NET Core interview questions and their answers are explained in simple and easy language.

Pre-requisite for .NET Core Interview

If you are preparing for .NET Core interview, then we assume that you have experience in C# coding and you are clear with object-oriented concept. If yes, then you are good to go.

Important ASP.Net Core Interview Questions and Answers

1. What is ASP.Net Core?

The ASP.Net Core is a new open-source framework introduced by Microsoft. ASP.Net Core is a cross-platform open-source framework for building modern applications including cloud-based development.

Features of ASP.Net Core

  • Develop cross platform application
  • Fast
  • Use of Razor pages
  • Dependency Injection

2. What are benefits of .Net Core?

  • It is a framework to build web applications
  • It is open source
  • Deploy .Net core application to on-premises or to the cloud.
  • Build and run the application on Windows, MAC, and Linux
  • A cloud-ready environment
  • Ability to host in IIS or self-host

3. ASP.Net vs ASP.Net Core

Dot Net Core is the latest version of ASP.Net framework and along with that ASP.Net Core is an open-source and cross platform framework which gives you privilege to develop modern web based and windows based application. ASP.Net based application can run on windows machine only.

But, the application developed in .Net Core is not bounded with any environment, you are free to host .Net Core based application on Windows, Mac or Linux machine. Note: No more ASPX pages in ASP.Net Core.

4. Versions of ASP.Net Core

Below table tells you the version details of ASP.Net Core (till July 2020) and their Long term support.

VersionReleasedLong Term Support
.Net Core 3.1December, 2019Yes
.Net Core 3.0September, 2019No
.Net Core 2.2December, 2018No
.Net Core 2.1May, 2018Yes
.Net Core 2.0August, 2017No
.Net Core 1.1November, 2016No
.Net Core 1.0June, 2016No

5. What is Kestrel?

Kestrel is a default web server used in ASP.Net Core application. Kestrel is a light-weight and cross platform web server. It supports SSL and doesn’t have advance features like IIS as it is a light-weight web server. It is included in Project.json file –

<'PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />

To install this through package manager, use below command –

Install-Package Microsoft.AspNetCore.Server.Kestrel -Version 2.2.0

6. What is Startup.cs file in ASP.Net Core?

From the .Net Core interview point of view, this is a very important question that you should focus on.

ASP.Net Core project includes Startup.cs file which gets executed as soon as applications gets started. It contains a ConfigureServices() and Configure() method which gets called by the runtime. We can get defined database connection string in this method with the help of IServiceCollection. ConfigureServices() is the method that we use to configure services required for our application. Below is the ConfigureServices() method in startup.cs file –

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

Below is the Config() method in startup.cs file –

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
         }

7. How to define URL rewriting in ASP.Net Core?

An URL redirection and rewriting task can be done in Configure() method of startup.cs file in ASP.Net Core. Below is the syntax to redirect

app.Use(async (context, next) =>
            {
                var url = context.Request.Path.Value;
                if (url.Contains("/old-page-url"))
                {
                    // rewrite and continue processing
                    context.Response.Redirect("/new-page-url",true);
                    return;
                }
               await next();
            });

In context.Response.Redirect, if you passed second parameter as true then your redirect will work as permanent redirect with 301 as HTTP status, which helps you in Search Engine Optimization (SEO).

8. AddSingleton() vs AddTransient() vs AddScope() in ASP.Net Core

This is also a more frequently asked question in .Net Core interviews.

All these 3 methods are very important in ASP.Net Core, they have their own significance of using in your application. Also, this is on of the most important ASP.Net Core interview question. Let’s see them one by one.

AddSingleton() Method

In AddSingleton() method, only one instance of service is created, when the service is executed at very first time. So, a single instance is created for a service , no matter how many times the service is being executed.

AddTransient() Method

With AddTransient() method, it creates new instance every time a service request is raised, doesn’t matter it is in the same HTTP request or different HTTP request.

AddScope() Method

With AddScope() method, we get new instance with different http requests. But we get same instance if it is within the same scope.

We use these methods in ConfigureServices() method in startup.cs file

    public void ConfigureServices(IServiceCollection services)
        {
         services.AddSingleton<'IProductRepository, ProductRepository'>();
    }

    public void ConfigureServices(IServiceCollection services)
    {
    services.AddTransient<'IProductRepository, ProductRepository'>();
        }

        public void ConfigureServices(IServiceCollection services)
        {
        services.AddScoped<'IProductRepository, ProductRepository'>();
            }
For more details about AddTransient(), AddScoped() and AddSingleton(), read this article - AddTransient, AddScoped and AddSingleton Services Differences
Watch Video of AddTransient vs AddScoped vs AddSingleton in .NET Core

9. Explain ASP.Net Core Middleware

One of the important .Net Core interview questions.

Middleware is a component which gets executed every time a request is made to the ASP.Net Core application. Middleware is similar to HttpHandlers and HttpModules of traditional ASP.Net. In ASP.Net Core, Request delegates are used to build the request pipeline to handle each and every HTTP request. Request delegates can be configured using Run(), Map() or Use() extension methods. We can use these methods in Configure() method of startup.cs file

Middleware in .NET Core

Run() Method

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hey There...");
        });
    }
}

Use() Method

For eg – If you want to redirect your one of old page to the new page, then you have to check each http request to match the UTL containing your old page URL and then redirect to new page.

app.Use(async (context, next) =>
            {
                var url = context.Request.Path.Value;
  if (url.Contains("/old-page-url"))
                {
                    context.Response.Redirect("/new-page-url",true);
                    return;
                }
   await next();
            });

10. What is API Documentation in ASP.Net Core?

This is another important questions asked to .Net Core Developer.

API documentation is used to help client or non-technical users to understand the .Net Core end points.

This can be done with the help of Swagger. Swaager is an open source technology used for API documentation.

To use Swagger, developer needs to install this package – Swashbuckle.AspnetCore

services.AddSwaggerGen(c=>c.SwaggerDoc("V1", new Info() {Title="My API Doc", Version="V1"}));

In above code V1 is the version number of your API.

11. What is Razor Pages?

Razor pages are the next evolution of traditional ASP.Net WebForms. File extension of razor pages is .cshtml ASP.Net Core Razor Page is very similar to ASP.NET MVC’s view pages. It has a similarity in syntax and functionality as MVC. The major difference is that in an MVC application model and controller code is included or bonded with View pages. Razor Pages vs MVC in .Net Core

12. How to define Database connection string in ASP.Net Core?

A database connection string is a very basic task for a developer. But defining a database connection string in .Net Core and reading back into C# code is a little different than the traditional ASP.Net framework. In .Net core, we don’t have web.config like ASP.Net framework. In ASP.Net Core we have JSON based file to manage database connection string.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost\SQLEXPRESS;Database=Test;Trusted_Connection=Yes;Integrated Security=SSPI;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

If you are using entity framework core then, get the connection name in ConfigureServices() method defined in startup.cs file.

 services.AddDbContext(options =>
       options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

In general, use below code to read and use database connection string defined in appsettings.json file

var dbconfig = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json").Build();

if (!string.IsNullOrEmpty(dbconfig.ToString()))
                {
                    string dbconnectionStr = dbconfig["ConnectionStrings:DefaultConnection"];
                }

13. How to implement Routing in ASP.Net Core?

Routing is a mechanism to match incoming HTTP request and then tranfer those request to matching endpoint URL. You will find a defined route in startup.cs file when you create an ASP.Net Core project. In Configure() method, below is the pre-defined routing

  app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

You can define attribute routing in Controller class of ASP.Net Core application –

  [HttpGet("/my-dashboard")]
        public IActionResult Dashboard()
        {
            var listData = _context.DashboardData.OrderBy(x=>Guid.NewGuid()).ToList().Take(10);
            return View(listData);
        }

14. wwwroot folder in .Net Core

This is a question related to the .Net Core project structure.

wwwroot folder in ASP.Net Core application contains static files for eg images, stylesheets, script files. It is treated as root folder of .Net Core web application.

15. What is tag helper in ASP.Net Core?

This is a completely new concept used in the Razor view engine. Tag Helpers helps server side code to create and render HTML tags in Razor View engine. It does the same thing as HTML Helpers does in previous versions of MVC but with a variety of changes. It enables IntelliSense, which allow to build HTML markup in easy way.

16. What are JSON files available in ASP.Net Core project?

Below are the JSON files available in ASP.Net Core project

  • global.json
  • appsettings.json
  • package.json
  • launchsettings.json
  • bundleconfig.json

17. What’s new in .Net Core 3.1 ?

Support of C++/CLI – Support added to create and develop C++/CLI projects. Binaries produced from these projects are compatible with .NET Core 3.0 and later versions.

appHost – When the appHost setting is enabled, .NET Core generates a native Mach-O executable when you build or publish. Your app runs in the context of the appHost when it is run from source code with the dotnet run command, or by starting the Mach-O executable directly.

You can configure the appHost at the project level using below xml code.

<PropertyGroup>

<UseAppHost>true</UseAppHost>

</PropertyGroup>

18. Dot Net Core 3.1 is available in which version of Visual Studio?

If you’re using Visual Studio 2019, you must update to Visual Studio 2019 version 16.4 or later to work with .NET Core 3.1 projects.

19. What are key changes in .NET Core compare to .NET Framework?

ASP.Net Web Forms, Windows Workflow Foundation and ADO.Net Data Services not supported in .NET Core.

Instead of Web Forms, we can use Razor Pages to develop apps in .NET Core.

For detailed comparison between .NET Core and .Net Framework, follow this article – .NET Core vs .Net Framework

20. What’s new in .NET 5?

Below are few major changes in .NET 5

  • .NET 5 supports C#9 and F#6.
  • It supports WindowsArm64
  • Improved performance of System.Text.Json
  • Cross-Platform support for System.DirectoryServices.Protocols to work with Directory Services on Linux and MacOs

21. Where to use .NET 5?

Use .NET 5 for below reasons –

  • You need cross-platform application
  • If, You are planning for Microservice architecture
  • You are using Docker containers.
For more details about .NET 5 new features, follow this article - What's new in .NET 5?

22. How to work with .NET 5 in Visual Studio Code?

In order to work with .NET5 in Visual Studio Code, we need to download .NET 5.0 SDK for Visual Studio Code from below link –

Download .NET Core SDK for Visual Studio Code (microsoft.com)

Download Visual Studio Code from below link –

Download Visual Studio Code – Mac, Linux, Windows

Next, install some extensions in Visual Studio Code.

Watch this Video to know how to create .NET 5 API using Visual Studio Code.

.NET5 API with Visual Studio Code

23. What is Secret Manager in ASP.Net Core?

This is a common interview question for .Net Core developer.

The Secret Manager tool in ASP.Net Core stores confidential information out side of the project during the development phase. In Windows Machine, secrets.json file path is

%APPDATA%\Microsoft\UserSecrets\<user_secrets_id>\secrets.json

To Create User Secrets –

  • Right click on project name in Solution explorer.
  • Select Manage User Secrets. You may notice that a JSON file secrets.json is now created.
  • Now cut the connection string node from appsettings.json file and paste it into secrets.json file.
  • Build your project and run your application. It should work perfectly.

Secret Manager works only in development machine.

For more details visit this link – What is Secret Manager in ASP.Net Core?

24. How to implement Dependency Injection in .NET 5?

This is one of the most frequently asked .Net Core interview Question.

.NET 5 supports the dependency injection (DI) software design pattern, which is a procedure for accomplishing Inversion of Control (IoC) among classes and their conditions.

Dot Net 5 injects objects of dependency classes using a constructor or a method by utilizing IoC container.

ASP.Net Core or .NET 5 allows us to enlist our application code with IoC container, in the ConfigureServices method of Startup class (startup.cs).

The ConfigureServices method incorporates a parameter of IServiceCollection type which is utilized to enroll application services.
A service can be injected into the Startup constructor and the Startup.Configure method.

For details about Dependency Injection in .Net 5, visit this link – How to implement Dependency Injection in .NET 5?

25. What is appsettings.Environment.json file in .Net Core?

By default, an appsettings.json file and appsettings.Development.json file is created in .NET Core project.

We can create multiple appsettings file based on environment in .Net Core, for development we have appsettings.Development.json, for staging we can create appsettings.Staging.json and for production we can have appsettings.Production.json file.

For more details about appsettings.json file in ASP.Net Core, visit this link – How to use appsettings.json configuration in ASP.NET Core?

26. What are differences between .Net Framework vs .NET Core vs .Net 5 ?

ASP.NET Framework is a Windows-only version of .NET for building any type of app that runs on Windows. It means .Net framework is built for Windows machine only. 

.NET Core is a free, cross-platform, open-source developer platform for building many different types of applications. The first version .Net Core 1.0 was released in June 2016 and the last version of .Net Core is 3.1 which was released in Dec, 2019.

.NET 5 is a free, cross-platform, open-source developer platform for building many different types of applications. .NET 5 is the next major release after .Net Core 3.1 which was released in June, 2016.

The word ‘Core’ is dropped from the name to emphasize that .NET 5 is the future of all earlier versions of .NET Core.

.Net Framework vs .NET Core vs .NET 5

27. Create a .NET 5 Web API project to perform CRUD operation.

To know how to create .NET 5 Web API project, read this – How to Build .NET 5 Web API in Visual Studio 2019?

To Create a .NET 5 Web API and Angular application to perform CRUD operation with the help of Entity Framework Core, read this – .NET 5 Web API CRUD with Angular and Entity Framework

Read this - How to create .NET 5 API in Visual Studio Code?

28. How to implement Repository pattern in ASP.Net Core project?

It is a very popular design pattern used widely.

To implement repository pattern in ASP.Net Core project, follow this –

  • Create an interface and declare the methods inside this interface.
  • Add a repository class and implement the interface created in step 1.
  • Place DbContext dependent code in Repository class.
  • Register Interface and repository class in startup.cs
  • In Controller class, call the CRUD methods defined in interface.

29. What is Content Negotiation?

In REST API, there is a defined format for Input and Output data.

By default, ASP.Net Core API supports JSON format.

To get response in XML format, add below line in ConfigureService() method in startup.cs file

services.AddXmlSerializerFormatter();

Now, if you provide accept header value to application/xml then API will respond in XML format.

30. What is ASP.Net Core Identity?

ASP.Net Core Identity provides a wide range of helper functions to perform essential core features related to user identity management. For example – Password hash, Account Confirmation, Multifactor Authentication etc.

31. What is Stateful and Stateless authentication?

Stateful AuthenticationStateless Authentication
It means that server keep tracks the session and a cookie is created in user’s browser.Each request is tied with a token to verify the request. It uses JWT (JSON Web Token) to validate the user.
It is called Cookie based authentication.It is called Token based authentication.

32. What is DbContext in .Net Core?

DbContext class act as a middleware or gateway to the database. It comes under Microsoft.EntityFrameworkCore

For example, I have created a MyAppDBContext class which looks like this –

public partial class MyAppDBContext : DbContext
    {
  
        public MyAppDBContext(DbContextOptions<MyAppDBContext> options)
            : base(options)
        {
             
        }
}

33. What is Middleware in ASP NET Core?

A middleware in .Net Core is a component which gets executed on every request and response in an ASP.Net Core application. Middleware component has the access to request and response process.

Middleware is used in Configure() method in startup.cs file.

Some of the Middleware used in ASP.Net Core application are –

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

app.UseRouting();

app.UseAuthorization();

Another Middleware used in ASP.Net Core

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

Middleware are executed in the order they are added in Configure() method.

We can create custom Middleware and can use multiple middleware in ASP.Net Core application.

34. How to use Custom Middleware in ASP.Net Core application?

One or multiple Middleware can be used in .Net Core application.

We can write custom Middleware using, Use() or Run() extension methods.

Middleware in .NET Core
app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Hello World From 1st Middleware!  ");

                await next();
            });

35. Use() vs Run() method in .Net Core

Use() and Run() are extension methods, they are used to implement Middleware in ASP.Net Core project.

With the help of Use() method, we can point to next middleware in our application, whereas Run() is used for terminal middleware. Terminal middleware means, there is no next middleware to execute.

So, use Run() either for last middleware or if there is no middleware to execute after that.

Use() method-

 app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("Hello World From 1st Middleware!  ");
                await next();

            });

Run() method-

app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World From Terminal Middleware!");
            });

36. What is ConfigureServices() in .NET Core?

ConfigureServices() method is defined in startup.cs file. It is used to register the service classes available in ASP.NET Core application.

public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IService1, Service1>();
}

37. What is Configure() method in .NET Core?

This method gets called by the runtime. Use this method to configure the HTTP request pipeline. use Configure() method to add middleware().

Read this – Middleware in .ASP.Net Core

Syntax to add a middleware inside Configure() method.

 app.Run(async (context) =>
                {
                    await context.Response.WriteAsync("First Middleware");
                     
            });

38. What is Service Lifecycle?

We can register service based on requirement. There are 3 different ways to register services based on lifecycle.

  • AddTransient()
  • AddSingleton()
  • AddScoped()

Hope these .Net Core interview questions and answers are helpful to you. Please share this within your community and comment below in case you have any feedback.

Conclusion:

I have added most of the asked ASP.NET Core Interview Questions and their answers in easy language. Above given interview questions are suitable for entry level and mid level developers. Whenever I get new .NET Core interview questions, I will keep updating this article.

Good Luck for your interview

Please follow and like us:

Leave a Comment