Net Core Interview Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

What is .NET Core?

The .NET Core platform is a new .NET stack that is optimized for open
source development and agile delivery on NuGet.
.NET Core has two major components. It includes a small runtime that is
built from the same codebase as the .NET Framework CLR. The .NET
Core runtime includes the same GC and JIT (RyuJIT), but doesn’t include
features like Application Domains or Code Access Security. The runtime is
delivered via NuGet, as part of the ASP.NET Core package.
.NET Core also includes the base class libraries. These libraries are largely
the same code as the .NET Framework class libraries, but have been
factored (removal of dependencies) to enable to ship a smaller set of
libraries. These libraries are shipped as System.* NuGet packages on
NuGet.org.

Can ASP.NET Core work with the .NET framework?


Yes. This might surprise many, but ASP.NET Core works with .NET
framework and this is officially supported by Microsoft.
ASP.NET Core works with:

 .NET Core framework


 .NET framework

What are some characteristics of .NET Core?


 Flexible deployment: Can be included in your app or installed side-
by-side user- or machine-wide.
 Cross-platform: Runs on Windows, macOS and Linux; can be
ported to other OSes. The supported Operating Systems (OS), CPUs
and application scenarios will grow over time, provided by Microsoft,
other companies, and individuals.
 Command-line tools: All product scenarios can be exercised at the
command-line.
 Compatible: .NET Core is compatible with .NET Framework,
Xamarin and Mono, via the .NET Standard Library.
 Open source: The .NET Core platform is open source, using MIT
and Apache 2 licenses. Documentation is licensed under CC-BY.
.NET Core is a .NET Foundation project.
 Supported by Microsoft: .NET Core is supported by Microsoft,
per .NET Core Support

What is CTS?
The Common Type System (CTS) standardizes the data types of all
programming languages using .NET under the umbrella of .NET to a
common data type for easy and smooth communication among these .NET
languages.
CTS is designed as a singly rooted object hierarchy
with System.Object as the base type from which all other types are
derived. CTS supports two different kinds of types:

1. Value Types: Contain the values that need to be stored directly on


the stack or allocated inline in a structure. They can be built-in
(standard primitive types), user-defined (defined in source code) or
enumerations (sets of enumerated values that are represented by
labels but stored as a numeric type).
2. Reference Types: Store a reference to the value‘s memory address
and are allocated on the heap. Reference types can be any of the
pointer types, interface types or self-describing types (arrays and
class types such as user-defined classes, boxed value types and
delegates).

What is the difference between .NET Core and Mono?


To be simple:

 Mono is third party implementation of .Net Framework for


Linux/Android/iOs
 .Net Core is Microsoft's own implementation for same.
What's the difference between SDK and Runtime in .NET
Core?
 The SDK is all of the stuff that is needed/makes developing a .NET
Core application easier, such as the CLI and a compiler.
 The runtime is the "virtual machine" that hosts/runs the application
and abstracts all the interaction with the base operating system.

Explain the difference between Task and Thread in .NET


 Thread represents an actual OS-level thread, with its own stack and
kernel resources. Thread allows the highest degree of control; you
can Abort() or Suspend() or Resume() a thread, you can observe
its state, and you can set thread-level properties like the stack size,
apartment state, or culture. ThreadPool is a wrapper around a pool
of threads maintained by the CLR.

 The Task class from the Task Parallel Library offers the best of both
worlds. Like the ThreadPool, a task does not create its own OS
thread. Instead, tasks are executed by a TaskScheduler; the default
scheduler simply runs on the ThreadPool. Unlike the ThreadPool,
Task also allows you to find out when it finishes, and (via the generic
Task) to return a result.
Explain what is included in .NET Core?
 A .NET runtime, which provides a type system, assembly loading, a
garbage collector, native interop and other basic services.
 A set of framework libraries, which provide primitive data types, app
composition types and fundamental utilities.
 A set of SDK tools and language compilers that enable the base
developer experience, available in the .NET Core SDK.
 The 'dotnet' app host, which is used to launch .NET Core apps. It
selects the runtime and hosts the runtime, provides an assembly
loading policy and launches the app. The same host is also used to
launch SDK tools in much the same way.
What are the benefits of Explicit Compilation (AOT)?
Ahead of time (AOT) delivers faster start-up time, especially in large
applications where much code executes on startup. But it requires more
disk space and more memory/virtual address space to keep both the IL and
precompiled images. In this case the JIT Compiler has to do a lot of disk
I/O actions, which are quite expensive.

What is CoreCLR?
CoreCLR is the .NET execution engine in .NET Core, performing functions
such as garbage collection and compilation to machine code.
Consider:

What is JIT compiler?


Before a computer can execute the source code, special programs called
compilers must rewrite it into machine instructions, also known as object
code. This process (commonly referred to simply as “compilation”) can be
done explicitly or implicitly.
Implicit compilation is a two-step process:
 The first step is converting the source code to intermediate language
(IL) by a language-specific compiler.

The second step is converting the IL to machine instructions. The main


difference with the explicit compilers is that only executed fragments of IL
code are compiled into machine instructions, at runtime. The .NET
framework calls this compiler the JIT (Just-In-Time) compiler.

What is Kestrel?
 Kestrel is a cross-platform web server built for ASP.NET Core based
on lib uv – a cross-platform asynchronous I/O library.
 It is a default web server pick since it is used in all ASP.NET Core
templates.
 It is really fast.

It is secure and good enough to use it without a reverse proxy server.


However, it is still recommended that you use IIS, Nginx or Apache or
something else.

What is difference between .NET Core and .NET


Framework?
.NET as whole now has 2 flavors:

 .NET Framework
 .NET Core

.NET Core and the .NET Framework have (for the most part) a subset-
superset relationship. .NET Core is named “Core” since it contains the core
features from the .NET Framework, for both the runtime and framework
libraries. For example, .NET Core and the .NET Framework share the GC,
the JIT and types such as String and List.

.NET Core was created so that .NET could be open source, cross platform
and be used in more resource-constrained environments.
When should we use .NET Core and .NET Standard Class
Library project types?
 Use a .NET Standard library when you want to increase the number
of apps that will be compatible with your library, and you are okay
with a decrease in the .NET API surface area your library can access.
 Use a .NET Core library when you want to increase the .NET API
surface area your library can access, and you are okay with allowing
only .NET Core apps to be compatible with your library.

Describe the ASP.NET Core.


ASP.NET Core is an open-source, cross-platform and high performance platform
that allows you to build modern, Internet-connected and cloud enabled
applications. With ASP.NET Core you can

 Build web applications, IoT (Internet of things) apps, services and mobile
Back ends.
 Run on .Net Core.
 You can do your development on Linux, Windows and MacOS.
 Deploy your code to cloud or on-premises.

What are the benefits of using ASP.NET Core over ASP.NET?


ASP.NET Core comes with the following benefits over ASP.NET.

 Cross platform, provide ability to develop and run on Windows, Linux and
MacOS.
 Open-source
 Unified Platform to develop Web UI and services.
 Built-in dependency injection.
 Ability to deploy on more than one server like IIS, Kestrel, Nginx, Docker,
Apache etc
 Cloud enabled framework, provide support for environment based
configuration systems.
 Lightweight, High performance and modern HTTP request pipelines.
 well suited architecture for testability
 Integration of many client-side frameworks like Angular any version.
 Blazor allow you to use C# code in browser with JavaScript code.

What is the role of Startup class?


Startup class is responsible for configuration related things as below.

 It configures the services which are required by the app.


 It defines the app's request handling pipeline as a series of middleware
components.
// Startup class example
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)


{
services.AddRazorPages();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
// other middleware components
}
}
 Startup class is specified inside the 'CreateHostBuilder' method when the
host is created. Multiple Startup classes can also be defined for different
environments, At run time appropriate startup class is used.
What is the role of ConfigureServices and Configure method?
ConfigureServices method is optional and defined inside startup class as
mentioned in above code. It gets called by the host before the 'Configure' method
to configure the app's services.

Configure method is used to add middleware components to the


IApplicationBuilder instance that's available in Configure method. Configure
method also specifies how the app responds to HTTP request and response.
ApplicationBuilder instance's 'Use...' extension method is used to add one or more
middleware components to request pipeline.

You can configure the services and middleware components without the Startup
class and it's methods, by defining this configuration inside the Program class
in CreateHostBuilder method.

Describe the Dependency Injection.


Dependency Injection is a Design Pattern that's used as a technique to achieve
the Inversion of Control (IoC) between the classes and their dependencies.
ASP.NET Core comes with a built-in Dependency Injection framework that makes
configured services available throughout the application. You can configure the
services inside the ConfigureServices method as below.

services.AddScoped();

A Service can be resolved using constructor injection and DI framework is


responsible for the instance of this service at run time.

What problems does Dependency Injection solve?


Let's understand Dependency Injection with this C# example. A class can use a
direct dependency instance as below.

Public class A {

MyDependency dep = new MyDependency();


public void Test(){

dep.SomeMethod();

But these direct dependencies can be problematic for the following reasons.

• If you want to replace 'MyDependency' with a different implementation


then the class must be modified.

• It's difficult to Unit Test.

• If MyDependency class has dependencies then it must be configured by


class. If Multiple classes have dependency on 'MyDependency', the code becomes
scattered.

DI framework solves these problems as below.

• Use Interfaces or base class to abstract the dependency implementation.

• Dependencies are registered in the Service Container provided by ASP.NET


Core inside Startup class 'ConfigureServices' method.

• Dependencies are injected using constructor injection and the instance is


created by DI and destroyed when no longer needed.

Describe the Service Lifetimes


When Services are registered, there is a lifetime for every service. ASP.NET Core
provide following lifetimes.

• Transient - Services with transient lifetime are created each time they are
requested from service container. So it's best suited for stateless, light weight
services.
• Scoped - Services with scoped lifetime are created once per connection or
client request. When using scoped service in middleware then inject the service
via invoke or invokeAsync() method. You should not inject the service via
constructor injection as it treats the service behavior like Singleton.

• Singleton - Service with singleton lifetime is created once when first time
the service is requested. For subsequent requests same instance is served by
service container.

Explain the Middleware in ASP.NET Core


The Request handling pipeline is a sequence of middleware components where
each component performs the operation on request and either call the next
middleware component or terminates the request. When a middleware
component terminates the request, it's called Terminal Middleware as It prevents
next middleware from processing the request. You can add a middleware
component to the pipeline by calling .Use... extension method as below.

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

So Middleware component is program that's build into an app's pipeline to handle


the request and response. Each middleware component can decide whether to
pass the request to next component and to perform any operation before or after
next component in pipeline.

What is Request delegate?


Request delegates handle each HTTP request and are used to build request
pipeline. It can configure using Run, Map and Use extension methods. An request
delegate can be a in-line as an anonymous method (called in-line middleware) or
a reusable class. These classes or in-line methods are called middleware
components.
What is Host in ASP.NET Core?
Host encapsulates all the resources for the app. On startup, ASP.NET Core
application creates the host. The Resources which are encapsulated by the host
include:

• HTTP Server implementation

• Dependency Injection

• Configuration

• Logging

• Middleware components

Describe the Generic Host and Web Host.


The host setup the server, request pipeline and responsible for app startup and
lifetime management. There are two hosts:

• .NET Generic Host

• ASP.NET Core Web Host

.NET Generic Host is recommended and ASP.NET Core template builds a .NET
Generic Host on app startup.

ASP.NET Core Web host is only used for backwards compatibility.

// Host creation

public class Program

public static void Main(string[] args)

{
CreateWebHostBuilder(args).Build().Run();

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>

WebHost.CreateDefaultBuilder(args)

.UseStartup();

Describe the Servers in ASP.NET Core.

Server is required to run any application. ASP.NET Core provides an in-process


HTTP server implementation to run the app. This server implementation listen for
HTTP requests and surface them to the application as a set of request features
composed into an HttpContext.

ASP.NET Core use the Kestrel web server by default. ASP.NET Core comes with:

• Default Kestrel web server that's cross platform HTTP server


implementation.

• IIS HTTP Server that's in-process server for IIS.

• HTTP.sys server that's a Windows-only HTTP server and it's based on the
HTTP.sys kernel driver and HTTP Server API.

How Configuration works in ASP.NET Core?


In ASP.NET Core, Configuration is implemented using various configuration
providers. Configuration data is present in the form of key value pairs that can be
read by configuration providers as key value from different configuration sources
as below.

• appsettings.json - settings file

• Azure Key Vault


• Environment variables

• In-memory .Net objects

• Command Line Arguments

• Custom Providers

By default apps are configured to read the configuration data from


appsettings.json, environment variables, command line arguments etc. While
reading the data, values from environment variables override appsettings.json
data values. 'CreateDefaultBuilder' method provide default configuration.

How to read values from Appsettings.json file?


You can read values from appsettings.json using below code.

class Test{

// requires using Microsoft.Extensions.Configuration;

private readonly IConfiguration Configuration;

public TestModel(IConfiguration configuration)

Configuration = configuration;

// public void ReadValues(){

var val = Configuration["key"]; // reading direct key values

var name = Configuration["Employee:Name"]; // read complex values

}
}

Default configuration provider first load the values from appsettings.json and
then from appsettings.Environment.json file.

Environment specific values override the values from appsettings.json file. In


development environment appsettings.Development.json file values override the
appsettings.json file values, same apply to production environment.

You can also read the appsettings.json values using options pattern described
Read values from appsettings.json file.

What is the Options Pattern in ASP.NET Core?


Options Pattern allow you to access related configuration settings in Strongly
typed way using some classes. When you are accessing the configuration settings
with the isolated classes, The app should adhere these two principles.

• Interface Segregation Principle (ISP) or Encapsulation: The class the depend


on the configurations, should depend only on the configuration settings that they
use.

• Separation of Concerns: Settings for different classes should not be related


or dependent on one another.

How to use multiple environments in ASP.NET Core?


ASP.NET Core use environment variables to configure application behavior based
on runtime environment. launchSettings.json file sets
ASPNETCORE_ENVIRONMENT to Development on local Machine. For more visit
How to use multiple environments in ASP.NET Core.

How Routing works in ASP.NET Core?


Routing is used to handle incoming HTTP requests for the app. Routing find
matching executable endpoint for incoming requests. These endpoints are
registered when app starts. Matching process use values from incoming request
url to process the requests. You can configure the routing in middleware pipeline
of configure method in startup class.

app.UseRouting(); // It adds route matching to middlware pipeline

// It adds endpoints execution to middleware pipeline

app.UseEndpoints(endpoints =>

endpoints.MapGet("/", async context =>

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

});

});

For more you can refer ASP.NET Core Routing.

How to handle errors in ASP.NET Core?


ASP.NET Core provides a better way to handle the errors in Startup class as below.

if (env.IsDevelopment())

app.UseDeveloperExceptionPage();

else

app.UseExceptionHandler("/Error");
app.UseHsts();

For development environment, Developer exception page display detailed


information about the exception. You should place this middleware before other
middlewares for which you want to catch exceptions. For other environments
UseExceptionHandler middleware loads the proper Error page.

You can configure error code specific pages in Startup class Configure method as
below.

app.Use(async (context, next) =>

await next();

if (context.Response.StatusCode == 404)

context.Request.Path = "/not-found";
await next();
}

if (context.Response.StatusCode == 403 || context.Response.StatusCode ==


503 || context.Response.StatusCode == 500)

context.Request.Path = "/Home/Error";

await next();

});
How ASP.NET Core serve static files?
In ASP.NET Core, Static files such as CSS, images, JavaScript files, HTML are the
served directly to the clients. ASP.NET Core template provides a root folder called
wwwroot which contains all these static files. UseStaticFiles() method inside
Startup.Configure enables the static files to be served to client.

You can serve files outside of this webroot folder by configuring Static File
Middleware as following.

app.UseStaticFiles(new StaticFileOptions

FileProvider = new PhysicalFileProvider(

Path.Combine(env.ContentRootPath, "MyStaticFiles")), // MyStaticFiles is


new folder

RequestPath = "/StaticFiles" // this is requested path by client

});

// now you can use your file as below

<img src="/StaticFiles/images/profile.jpg" class="img" alt="A red rose" />

// profile.jpg is image inside MyStaticFiles/images folder

Explain Session and State management in ASP.NET Core


As we know HTTP is a stateless protocol. HTTP requests are independent and
does not retain user values. There are different ways to maintain user state
between multiple HTTP requests.

• Cookies

• Session State

• TempData
• Query strings

• Hidden fields

• HttpContext.Items

• Cache

Explain the Caching or Response caching in ASP.NET Core.


Caching significantly improves the performance of an application by reducing the
number of calls to actual data source. It also improves the scalability. Response
caching is best suited for data that changes infrequently. Caching makes the copy
of data and store it instead of generating data from original source.

Response caching headers control the response caching. ResponseCache attribute


sets these caching headers with additional properties.

What is In-memory cache?


In-memory cache is the simplest way of caching by ASP.NET Core that stores the
data in memory on web server.

Apps running on multiple server should ensure that sessions are sticky if they are
using in-memory cache. Sticky Sessions responsible to redirect subsequent client
requests to same server. In-memory cache can store any object but distributed
cache only stores byte[].

IMemoryCache interface instance in the constructor enables the In-memory


caching service via ASP.NET Core dependency Injection.

What is Distributed caching?


Applications running on multiple servers (Web Farm) should ensure that sessions
are sticky. For Non-sticky sessions, cache consistency problems can occur.
Distributed caching is implemented to avoid cache consistency issues. It offloads
the memory to an external process. Distributed caching has certain advantages as
below.

• Data is consistent across client requests to multiple server

• Data keeps alive during server restarts and deployments.

• Data does not use local memory

IDistributedCache interface instance from any constructor enable distributed


caching service via Dependency Injection.

What is XSRF or CSRF? How to prevent Cross-Site Request


Forgery (XSRF/CSRF) attacks in ASP.NET Core?
Cross-Site Request Forgery (XSRF/CSRF) is an attack where attacker that acts as a
trusted source send some data to a website and perform some action. An attacker
is considered a trusted source because it uses the authenticated cookie
information stored in browser.

For example a user visits some site 'www.abc.com' then browser performs
authentication successfully and stores the user information in cookie and perform
some actions, In between user visits some other malicious site 'www.bad-
user.com' and this site contains some code to make a request to vulnerable site
(www.abc.com). It's called cross site part of CSRF.

How to prevent CSRF?

• In ASP.NET Core 2.0 or later FormTaghelper automatically inject the


antiforgery tokens into HTML form element.

• You can add manually antiforgery token in HTML forms by using


@Html.AntiForgeryToken() and then you can validate it in controller by
ValidateAntiForgeryToken() method.

• For more you can visit Prevent Cross-Site Request Forgery (XSRF/CSRF)
What is the main reason of using .Net core rather than
MVC ?
Net core has following benefits over .NET framework
 Cross platform support
 Best suited for developing scalable & independent micro services
 Built in Dependency injection
 Open source
 CLI support
 Self contained - Does not require any software to be installed on target
machine/server
 Low cost- Runs on VS code.

What is the purpose of Program.cs file in .NET Core project?


.NET Core Applications are console applications. Program.cs is the entry Point for
application. Like any application the execution of Application starts from public
static void Main(string[] args){}

This Program.cs creates the application Host. It configures the setiings file like
appsettings.json,logging using CreateDefaultBuilder(args) and Startup.cs through
webBuilder.UseStartup() which further helps in building dependencies.

What are the differences between ConfigureServices and


Configure Method in Startup class?
ConfigureServices method gets call runtime to register services to DI container.
After registering the dependent classes, you can use those classes anywhere in
the application. The ConfigureServices method includes the IServiceCollection
parameter to register services to the DI container
Configure the method gets call runtime to configure the HTTP request pipeline for
application. Configure use the instance of the IApplicationBuilder that is provided
by In-Build IOC container. In other words, you add the middleware in this method
like routing and other custom middleware as per your application requirements.
How to enable Session in ASP.NET Core?
The Microsoft.AspNetCore.Session package:
 Is included implicitly by the framework.
 Provides middleware for managing session state.
To enable the session middleware, Startup must contain:
1. Any of the IDistributedCache memory caches. The IDistributedCache
implementation is used as a backing store for session. For more information, see
Distributed caching in ASP.NET Core.
2. A call to AddSession in ConfigureServices.
3. A call to UseSession in Configure.
1. public void ConfigureServices(IServiceCollection services)
2. {
3. services.AddDistributedMemoryCache();
4.
5. services.AddSession(options =>
6. {
7. options.IdleTimeout = TimeSpan.FromSeconds(10);
8. options.Cookie.HttpOnly = true;
9. options.Cookie.IsEssential = true;
10. });
11.
12. //services.AddControllersWithViews();
13. //services.AddRazorPages();
14. }
app.UseSession(); in Configure method of startup.cs class.
This way you can enable session in asp.net core

What is the use of UseIISIntegration?


The ASP.NET Core Module generates a dynamic port to assign to the back-end
process. CreateDefaultBuilder calls the UseIISIntegration method, which picks up
the dynamic port and configures Kestrel to listen on http://localhost:500For more
Details go through the linkhttps://docs.microsoft.com/en-us/aspnet/core/host-
and-deploy/iis/?view=aspnetcore-2.1
What is launchsetting.json in ASP.NET Core?
You will find this file in the “Properties” folder in the project root folder.
The settings in this file are used when we run this ASP.NET core project either
from Visual Studio or by using .NET Core CLI.
This file is only used on local development machine. We do not need it for
publishing our asp.net core application.
If there are certain settings that you want your asp.net core application to use
when you publish and deploy your app, store them in appsettings.json file. We
usually store our application configuration settings in this file.
We can also have environment specific appsettings.json files. For example,
appsettings.Staging.json for the staging environment. In ASP.NET Core, in addition
to appsettings.json file, we also have other configuration sources like
Environment variables, User Secrets, Command Line Arguments and even our
own custom configuration source.
-------------------------------------------------------------------------------------------------------------
Other important questions…..
 Can ASP.NET Application be run in Docker containers?
 Explain Model Binding in ASP.NET Core.
 Explain Custom Model Binding.
 Describe Model Validation.
 How to write custom ASP.NET Core middleware?
 How to access HttpContext in ASP.NET Core?
 Explain the Change Token.
 How to used ASP.NET Core APIs in class library?
 What is the Open Web Interface for .NET (OWIN)?
 Describe the URL Rewriting Middleware in ASP.NET Core.
 Describe the application model in ASP.NET Core.
 How to prevent Cross-Site Scripting (XSS) in ASP.NET Core?
 How to enable Cross-Origin Requests (CORS) in ASP.NET Core?
 Describe the View components in ASP.NET Core.
 How View compilation works in ASP.NET Core?
 Explain Buffering and Streaming approaches to upload files in ASP.NET
Core.
 Explain dependency injection for controllers.
 How ASP.NET Core supports dependency injection into views?
 How will you unit test a controller?
 What is Cache Tag Helper in ASP.NET Core MVC?
 How validation works in MVC and how they follow DRY Pattern?
 Describe the complete request processing pipeline for ASP.NET Core MVC.

You might also like