In this article, we are going to cover Important ASP.NET Core interview questions and answers, which will help you to pass your next job interview.
.Net Core interview questions given below will prove to be very beneficial for both freshers and experienced developers. So, without delay, let’s read each interview question of ASP.Net Core and its answer because below are some of the most important ASP.NET Core interview questions and answers.
Below are the interview questions applied to .Net Core 2.1, .Net Core 3.1 and .Net 5 as well. The .NET Core interview questions and their answers are explained below in simple and easy language.
Pre-requisite for .NET Core Interview
If you are preparing for a .NET Core interview, then we assume that you have experience in C# coding and you are confident with the object-oriented concepts. If yes, then you are good to go.
Most 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 the benefits of .Net Core?
- It is a framework for building web applications
- It is open source
- Deploy .Net core application to on-premises or 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 the ASP.Net framework and along with that ASP.Net Core is an open-source and cross-platform framework that gives you the privilege to develop modern web-based and Windows-based applications. ASP.Net-based applications can run on Windows machines only.
But, the application developed in .Net Core is not bound to any environment, you are free to host .Net Core-based applications on Windows, Mac or Linux machines. Note that, no more ASPX pages in ASP.Net Core.
4. Versions of ASP.Net Core
The below table tells you the version details of ASP.Net Core (till July 2020) and their Long-term support.
Version | Released | Long Term Support |
---|---|---|
.Net Core 3.1 | December 2019 | Yes |
.Net Core 3.0 | September 2019 | No |
.Net Core 2.2 | December 2018 | No |
.Net Core 2.1 | May 2018 | Yes |
.Net Core 2.0 | August 2017 | No |
.Net Core 1.1 | November 2016 | No |
.Net Core 1.0 | June 2016 | No |
5. What is Kestrel?
Kestrel is a default web server used in ASP.Net Core applications. Kestrel is a lightweight and cross-platform web server. It supports SSL and doesn’t have advanced features like IIS as it is a lightweight web server. It is included in the Project.json
file –
<'PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
To install this through the package manager, use the below command –
Install-Package Microsoft.AspNetCore.Server.Kestrel -Version 2.2.0
6. What is the Startup.cs file in ASP.Net Core?
From the .Net Core interview point of view, this is one of the important ASP.NET Core interview questions that you should focus on.
ASP.Net Core project includes Startup.cs
file which gets executed as soon as applications get started. It contains a ConfigureServices() and Configure() method which gets called by the runtime. We can get a defined database connection string in this method with the help of IServiceCollection. ConfigureServices() is the method that we use to configure the 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?
URL redirection and the rewriting tasks can be done in the 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 pass the second parameter as true then your redirect will work as a 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 signs of use in your application. Also, this is one of the most important ASP.Net Core interview questions. Let’s see them one by one.
AddSingleton() Method
In AddSingleton() method, only one instance of service is created, when the service is executed for the 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 the AddTransient()
method, creates a new instance every time a service request is raised, doesn’t matter it is in the same HTTP request or a different HTTP request.
AddScope() Method
With the AddScope()
method, we get new instances with different HTTP requests. But we get the 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
9. Explain ASP.Net Core Middleware
One of the important .Net Core interview questions.
Middleware is a component that 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 one of the old pages 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 a 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 ASP.NET Core interview question.
API documentation is used to help the client or non-technical users understand the .Net Core endpoints.
This can be done with the help of Swagger. Swagger is an open-source technology used for API documentation.
To use Swagger, the developer needs to install this package – Swashbuckle.AspnetCore
services.AddSwaggerGen(c=>c.SwaggerDoc("V1", new Info() {Title="My API Doc", Version="V1"}));
In the 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. The 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 to MVC. The major difference is that in an MVC application model, controller code is included or bonded with View pages. Razor Pages vs MVC in .Net Core
12. How to define a 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 from 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 files to manage database connection strings.
{
"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 the ConfigureServices()
method defined in startup.cs file.
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
In general, use the below code to read and use the 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 requests and then transfer those requests to the 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 the Controller class of the 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 the ASP.Net Core application contains static files eg images, stylesheets, and script files. It is treated as the root folder of the .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 the 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 allows easy building of HTML markup.
16. What are JSON files available in the ASP.Net Core project?
Below are the JSON files available in the 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.
app host – When the app host 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 app host at the project level using the 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 the .NET Core compared to the .NET Framework?
ASP.Net Web Forms, Windows Workflow Foundation and ADO.Net Data Services are not supported in .NET Core.
Instead of Web Forms, we can use Razor Pages to develop apps in .NET Core.
For a 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 a 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 a 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 the below link –
Download .NET Core SDK for Visual Studio Code (microsoft.com)
Download Visual Studio Code from the below link –
Download Visual Studio Code – Mac, Linux, Windows
Next, install some extensions in Visual Studio Code.
Watch this video to learn how to create .NET 5 API using Visual Studio Code.
23. What is Secret Manager in ASP.Net Core?
This is a common interview question for .Net Core developers.
The Secret Manager tool in ASP.Net Core stores confidential information outside 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 the 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 intosecrets.json
file. - Build your project and run your application. It should work perfectly.
The secret Manager works only in the 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 Questions.
.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 an IoC container.
ASP.Net Core or .NET 5 allows us to enlist our application code with IoC container, in the ConfigureServices method of the Startup class (startup.cs
).
The ConfigureServices method incorporates a parameter of IServiceCollection type which is utilized to enrol 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 the .NET Core project.
We can create multiple appsettings files based on the 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 the 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 the .Net framework is built for Windows machines 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 operations 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 a Repository pattern in the ASP.Net Core project?
It is a very popular design pattern used widely.
To implement a repository pattern in the 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 the Repository class.
- Register Interface and repository class in startup.cs
- In the Controller class, call the CRUD methods defined in the 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 a response in XML format, add the below line in the 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 Authentication | Stateless Authentication |
It means that the server keeps track of the session and a cookie is created in the 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 acts as middleware or gateway to the database. It comes under Microsoft.EntityFrameworkCore
For example, I have created a MyAppDBContext class that 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 that gets executed on every request and response in an ASP.Net Core application. The middleware component has the access to request and response process.
Middleware is used in the Configure() method of 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 is executed in the order they have 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 the .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, that are used to implement Middleware in ASP.Net Core project.
With the help of the Use() method, we can point to the 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 the 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 the 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 services based on requirements. There are 3 different ways to register services based on the lifecycle.
- AddTransient()
- AddSingleton()
- AddScoped()
39. What is Blazor?
Blazor is Microsoft’s latest web framework technology. It is a new framework for developing client-side web UI which was introduced with .Net core 3.0. We generally use the C# code on the server side only, but with Blazor we can use the C# code on the client side as well.
Read the full article – What is Blazor in .NET Core?
40. What is the difference between Blazor Server and Blazor WebAssembly?
Blazor Server and Blazor WebAssembly have several differences. Blazor WebAssembly is also known as Blazor Wasm.
With the help of Blazor, we can write client-side functionality using C# programming. No more need for JavaScript.
Blazor Server uses ASP.Net Core application and we can use entity framework to connect with SQL Databases.
Blazor Wasm works on the browser and downloads the Blazor application on the client side. It supports all modern browsers.
To know the complete differences between Blazor Server and Blazor WebAssembly, read this article – Blazor Server and Blazor WebAssembly
41. How to Migrate .NET Core 2.2 Web API Project to .Net Core 3.1?
Software migration is always a risky and tedious task as there could be several impacts on the project.
Follow the below steps to migrate.
Step 1 – Open your project/ application in Visual Studio 2019
Step 2 – Right-click on your project name in Solution Explorer and select Edit Project file.
Change the target framework as per the below code snippet.
<TargetFramework>netcoreapp3.1</TargetFramework>
Step 3 – Open Startup.cs
file and follow the below changes.
Changes in ConfigureServices() method
Remove the below line from the ConfigureServices()
method.
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
And add this line in ConfigureServices() method-
services.AddControllers();
Changes in Configure() method
In the Configure()
method parameter, replace IHostingEnvironment with IWebHostEnvironment.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger)
You need to add this namespace – Microsoft.Extensions.Hosting;
Comment app.UseMvc()
in Configure()
method and add below code snippet below:
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Step 4 – Open Program.cs file
IWebHostBuilder
interface is now IHostBuilder.
Old Code snippet-
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
New code snippet –
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Read the Full Article here – Migrate from .NET Core 2.2 to 3.1
42. How to migrate the .NET Core 3.1 web API application to .NET 6?
To migrate from ASP.NET Core 3.1 to .NET 6, you should have the below tools, SDK, IDE –
- Visual Studio 2022
- .NET 6 SDK
- SQL Server 2017 and above
- Microsoft.EntityFrameworkCore.SqlServer 5.0.0
Read Full Article – https://www.sharepointcafe.net/2022/01/migrate-net-core-3-1-to-dot-net-6.html
43. What is SignalR in ASP.NET Core?
SignalR refers to a real-time application communication channel. It is a process that allows the integration of real-time functionality into your web applications.
The best example of a real-time-based application is a chat application, where the server sends content to the client as soon as it becomes available.
SignalR can be used to push notifications within an application. It uses encryption and a digital signature to make a secure communication channel.
Read the full article here to know how to implement SignalR in .NET Core – How to implement SignalR in ASP.NET Core?
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 important ASP.NET Core Interview Questions and their answers in easy language. The 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 with your interview