0% found this document useful (0 votes)
50 views18 pages

4 - .Net Core

Uploaded by

aitc.dba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views18 pages

4 - .Net Core

Uploaded by

aitc.dba
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

20 .

Net Core Interview Questions & Answers


ASP. NET Core is an open-source an asp.net core training cross-platform that runs on Windows,
Linux, and Mac to develop modern cloud-based applications including IoT apps, Web Apps,
Mobile Backends, and more. It is the fastest web development framework from NodeJS, Java
Servlet, PHP in raw performance, and Ruby on Rails.

Learning pedagogy has evolved with the advent of technology over the years. ASP.NET core
training will help you to know about this technology in a better way. Through the training
session, you would be able to know that ASP.NET core is not an upgraded version of ASP.NET.
ASP. NET Core is completely rewriting the work with the .NET framework. It is much faster,
modular, configurable, scalable, cross-platform, and extensible support of .NET world for which
organizations from different parts of the world are grabbing this technology in faster growth.
Even it can work with both .NET Core and .NET framework via the .NET standard framework.

Prepare yourself for the interview with the help of the ASP.NET Core interview question
answer Pdf file and get a suitable development position on the cloud-based application
including web application, IoT application, and Mobile application.

More: ASP.NET Core Interview Questions and Answers PDF Download

1. What is the ASP.NET Core?

ASP.NET Core is not an upgraded version of ASP.NET. ASP.NET Core is completely


rewriting that work with .net Core framework. It is much faster, configurable, modular,
scalable, extensible and cross-platform support. It can work with both .NET Core and .net
framework via the .NET standard framework. It is best suitable for developing cloud-
based such as web application, mobile application, IoT application.

2. What are the features provided by ASP.NET Core?

Following are the core features that are provided by the ASP.NET Core

o Built-in supports for Dependency Injection


o Built-in supports for the logging framework and it can be extensible
o Introduced new, fast and cross-platform web server - Kestrel. So, a web
application can run without IIS, Apache, and Nginx.
o Multiple hosting ways are supported
o It supports modularity, so the developer needs to include the module required by
the application. However, .NET Core framework is also providing the meta
package that includes the libraries
o Command-line supports to create, build and run the application
o There is no web.config file. We can store the custom configuration into an
appsettings.json file
o There is no Global.asax file. We can now register and use the services into startup
class
o It has good support for asynchronous programming

o Support WebSocket and SignalR


o Provide protection against CSRF (Cross-Site Request Forgery)
3. What are the advantages of ASP.NET Core over ASP.NET?

There are following advantages of ASP.NET Core over ASP.NET :

o It is cross-platform, so it can be run on Windows, Linux, and Mac.


o There is no dependency on framework installation because all the required
dependencies are ship with our application
o ASP.NET Core can handle more request than the ASP.NET
o Multiple deployment options available withASP.NET Core
4. What is Metapackages?

The framework .NET Core 2.0 introduced Metapackage that includes all the supported
package by ASP.NET code with their dependencies into one package. It helps us to do
fast development as we don't require to include the individual ASP.NET Core packages.
The assembly Microsoft.AspNetCore.All is a meta package provide by ASP.NET core.

5. Can ASP.NET Core application work with full .NET 4.x Framework?

Yes. ASP.NET core application works with full .NET framework via the .NET standard
library.

6. What is the startup class in ASP.NET core?

Startup class is the entry point of the ASP.NET Core application. Every .NET Core
application must have this class. This class contains the application configuration rated
items. It is not necessary that class name must "Startup", it can be anything, we can
configure startup class in Program class.

public class Program


{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

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


WebHost.CreateDefaultBuilder(args)
.UseStartup<TestClass>();
}

7. What is the use of ConfigureServices method of startup class?

This is an optional method of startup class. It can be used to configure the services that
are used by the application. This method calls first when the application is requested for
the first time. Using this method, we can add the services to the DI container, so services
are available as a dependency in controller constructor.

8. What is the use of the Configure method of startup class?

It defines how the application will respond to each HTTP request. We can configure the
request pipeline by configuring the middleware. It accepts IApplicationBuilder as a
parameter and also it has two optional parameters: IHostingEnvironment and
ILoggerFactory. Using this method, we can configure built-in middleware such as
routing, authentication, session, etc. as well as third-party middleware.

9. What is middleware?

It is software which is injected into the application pipeline to handle request and
responses. They are just like chained to each other and form as a pipeline. The incoming
requests are passes through this pipeline where all middleware is configured, and
middleware can perform some action on the request before passes it to the next
middleware. Same as for the responses, they are also passing through the middleware but
in reverse order.
10. What is the difference between IApplicationBuilder.Use() and
IApplicationBuilder.Run()?

We can use both the methods in Configure methods of startup class. Both are used to add
middleware delegate to the application request pipeline. The middleware adds using
IApplicationBuilder.Use may call the next middleware in the pipeline whereas the
middleware adds using IApplicationBuilder.Run method never calls the subsequent ore
next middleware. After IApplicationBuilder.Run method, system stop adding middleware
in request pipeline.

11. What is the use of "Map" extension while adding middleware to ASP.NET Core
pipeline?

It is used for branching the pipeline. It branches the ASP.NET Core pipeline based on
request path matching. If request path starts with the given path, middleware on to that
branch will execute.

public void Configure(IApplicationBuilder app)


{
app.Map("/path1", Middleware1);
app.Map("/path2", Middleware2);
}

12. What is routing in ASP.NET Core?

Routing is functionality that map incoming request to the route handler. The route can
have values (extract them from URL) that used to process the request. Using the route,
routing can find route handler based on URL. All the routes are registered when the
application is started. There are two types of routing supported by ASP.NET Core

o The conventional routing


o Attribute routing

The Routing uses routes for map incoming request with route handler and Generate URL
that used in response. Mostly, the application having a single collection of routes and this
collection are used for the process the request. The RouteAsync method is used to map
incoming request (that match the URL) with available in route collection.

13. How to enable Session in ASP.NET Core?

The middleware for the session is provided by the package


Microsoft.AspNetCore.Session. To use the session in ASP.NET Core application, we
need to add this package to csproj file and add the Session middleware to 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();
….
….
}
}

14. What are the various JSON files available in ASP.NET Core?

There are following JSON files in ASP.NET Core :

o global.json
o launchsettings.json
o appsettings.json
o bundleconfig.json
o bower.json
o package.json
15. What is tag helper in ASP.NET Core?

It is a feature provided by Razor view engine that enables us to write server-side code to
create and render the HTML element in view (Razor). The tag-helper is C# classes that
used to generate the view by adding the HTML element. The functionality of tag helper is
very similar to HTML helper of ASP.NET MVC.

Example:
//HTML Helper
@Html.TextBoxFor(model => model.FirstName, new { @class = "form-
control", placeholder = "Enter Your First Name" })

//content with tag helper


<input asp-for="FirstName" placeholder="Enter Your First Name"
class="form-control" />

//Equivalent HTML
<input placeholder="Enter Your First Name" class="form-control"
id="FirstName" name="FirstName" value="" type="text">

16. How to disable Tag Helper at element level?

We can disable Tag Helper at element level using the opt-out character ("!"). This
character must apply opening and closing the Html tag.

Example

<!span asp-validation-for="phone" class="divPhone"></!span>

17. What are Razor Pages in ASP.NET Core?

This is a new feature introduced in ASP.NET Core 2.0. It follows a page-centric


development model just like ASP.NET web forms. It supports all the feature of ASP.NET
Core.

Example

@page
<h1> Hello, Book Reader!</h1>
<h2> This is Razor Pages </h2>

The Razor pages start with the @page directive. This directive handle request directly
without passing through the controller. The Razor pages may have code behind file, but it
is not really code-behind file. It is class inherited from PageModel class.

18. How can we do automatic model binding in Razor pages?


The Razor pages provide the option to bind property automatically when posted the data
using BindProperty attribute. By default, it only binds the properties only with non-GET
verbs. we need to set SupportsGet property to true to bind a property on getting request.

Example

public class Test1Model : PageModel


{
[BindProperty]
public string Name { get; set; }
}

19. How can we inject the service dependency into the controller?

There are three easy steps to add custom service as a dependency on the controller.

Step 1: Create the service

public interface IHelloWorldService


{
string SaysHello();
}

public class HelloWorldService: IHelloWorldService


{
public string SaysHello()
{
return "Hello ";
}
}

Step 2: Add this service to Service container (service can either added by singleton,
transient or scoped)

public void ConfigureServices(IServiceCollection services)


{
….

services.AddTransient<IHelloWorldService, HelloWorldService>();


}

Step 3: Use this service as a dependency in the controller

public class HomeController: Controller


{
IHelloWorldService _helloWorldService;
public HomeController(IHelloWorldService helloWorldService)
{
_helloWorldService = helloWorldService;
}
}

20. How to specify service lifetime for register service that added as a dependency?

ASP.NET Core allows us to specify the lifetime for registered services. The service
instance gets disposed of automatically based on a specified lifetime. So, we do not care
about the cleaning these dependencies, it will take care by ASP.NET Core framework.
There is three type of lifetimes.

Singleton

ASP.NET Core will create and share a single instance of the service through the
application life. The service can be added as a singleton using AddSingleton method of
IServiceCollection. ASP.NET Core creates service instance at the time of registration and
subsequence request use this service instance. Here, we do not require to implement
Singleton design pattern and single instance maintained by the ASP.NET Core itself.

Example

services.AddSingleton<IHelloWorldService, HelloWorldService>();
Transient

ASP.NET Core will create and share an instance of the service every time to the
application when we ask for it. The service can be added as Transient using AddTransient
method of IServiceCollection. This lifetime can be used in stateless service. It is a way to
add lightweight service.

Example

services.AddTransient<IHelloWorldService, HelloWorldService>();
Scoped

ASP.NET Core will create and share an instance of the service per request to the
application. It means that a single instance of service available per request. It will create a
new instance in the new request. The service can be added as scoped using an AddScoped
method of IServiceCollection. We need to take care while, service registered via Scoped
in middleware and inject the service in the Invoke or InvokeAsync methods. If we inject
dependency via the constructor, it behaves like singleton object.

services.AddScoped<IHelloWorldService, HelloWorldService>();
ASP.NET Core Interview Questions
This post is about ASP.NET Core Interview Questions. These questions are guidelines to assess
the candidate about ASP.NET Core.These interview question covers basic to advance and will
help you to prepare for the interviews, quick revision and provide strength to your technical
skills.

Q. What is .NET Core?

Ans: .NET Core is a newer version of .NET, which is cross-platform, supporting Windows,
MacOS and Linux, and can be used in device, cloud, and embedded/IoT scenarios.

The following characteristics best define .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.

Q. How is it different from existing .NET framework?

Ans: Read Difference between .NET Core and .NET Framework

Q. What are .NET Platform Standards?

Ans: Read .NET Platform Standards

Q. What is ASP.NET Core?

Ans: ASP.NET Core 1.0 is the next version of ASP.NET. It is open source and cross-platform
framework (supports for Windows, Mac and Linux) suitable for building cloud based internet
connected applications like web apps, IoT apps and mobile apps. ASP.NET Core apps can run on
.NET Core or on the full .NET Framework.

Q. What are the newly introduced functionalities in ASP.NET Core?

Ans: Read Quick summary of what’s changed in ASP.NET Core. ASP.NET Core 2.0 is already
out and there are few changes and new things introduced. Read What’s new in ASP.NET Core 2
Q. Why Use ASP.NET Core for Web Application Development?

Ans: ASP.NET Core is an robust, and feature-rich framework that provides features to develop
super-fast APIs for web apps. ASP.NET Core should be prefered for following reason:

 ASP.NET Core is faster compare to traditional ASP.NET.


 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.
 Flexible deployment: Can be included in your app or installed side‐by‐side user or machine‐
wide. Runs on IIS or can be self‐hosted in your own process.
 Built‐in support for dependency injection.
 ASP.NET Core is cloud‐ready and has improved support for cloud deployment.
 Provides Support for Popular JavaScript Frameworks.
 Unification Of Development Models which allows the MVC and Web API development models to
use the same base class Controller.
 Razor Pages makes coding page‐focused scenarios easier and more productive.
 Environment based configuration supported for cloud deployment.
 Built in logging support.
 In ASP.NET we had modules and handlers to deal with requests. In ASP.NET Core we have
middleware which provides more control how the request should be processed as they are
executed in the order in which they are added.

Q. What is ASP.NET Core Middleware and How it is different from HttpModule?

Ans: Read my post about How ASP.NET Core 1.0 Middleware is different from HttpModule

Q. What are the various JSON files in ASP.NET Core?

Ans: Read my post about Various JSON files in ASP.NET Core

Q. What is Startup.cs file in ASP.NET Core?

Ans: In ASP.NET, Global.asax (though optional) acts as the entry point for your application.
Startup.cs, it is entry point for application itself. The Startup class configures the request pipeline
that handles all requests made to the application. Read this read this excellent post The Startup.cs
File in ASP.NET Core 1.0 – What Does It Do? to know more about startup.cs.

Q.What ConfigureServices() method does in Startup.cs?

Ans: This method is optional. It is the place to add services required by the application. For
example, if you wish to use Entity Framework in your application then you can add in this
method.
1
public void ConfigureServices(IServiceCollection services)
2
{
3 services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
4 services.AddEntityFramework()

5 .AddSqlServer()

6 .AddDbContext<SchoolContext>();

// Add MVC services to the services container.


7
services.AddMvc();
8
}
9

Q.What Configure() method does in Startup.cs?

Ans: The Configure method is used to specify how the ASP.NET application will respond to
HTTP requests. The request pipeline is configured by adding middleware components to an
IApplicationBuilder instance that is provided by dependency injection. There are some built-in
middlewares for error handling, authentication, routing, session and diagnostic purpose.
Highlighted lines in below code, are built-in Middleware with ASP.NET Core 1.0.

public void Configure(IApplicationBuilder app, IHostingEnvironment env,


1
ILoggerFactory loggerFactory)
2 {

3 loggerFactory.AddConsole(Configuration.GetSection("Logging"));

4 loggerFactory.AddDebug();

6 app.UseApplicationInsightsRequestTelemetry();

8 if (env.IsDevelopment())

{
9
app.UseBrowserLink();
1
0 app.UseDeveloperExceptionPage();

}
1
1 else

1 {
2 app.UseExceptionHandler("/Home/Error");
1
3
// For more details on creating database during deployment see
1 http://go.microsoft.com/fwlink/?LinkID=615859
4 try

1 {
5 using (var serviceScope =
app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
1
6 .CreateScope())

1 {
7 serviceScope.ServiceProvider.GetService<ApplicationDbContext
>()
1
8 .Database.Migrate();

1 }
9 }
2 catch { }
0
}
2
1
app.UseIISPlatformHandler(options =>
2 options.AuthenticationDescriptions.Clear());
2
app.UseStaticFiles();
2 app.UseIdentity();
3

2
4 // To configure external authentication please see
http://go.microsoft.com/fwlink/?LinkID=532715
2
5
app.UseMvc(routes =>
2
6 {

2 routes.MapRoute(
7 name: "default",

2 template: "{controller=Home}/{action=Index}/{id?}");
8 });
2 }
9
3
0

3
1

3
2

3
3

3
4

3
5

3
6

3
7

3
8

3
9

4
0

4
1

4
2

Q.What is the difference between app.Use vs app.Run while adding middleware?

Ans: Read app.Use vs app.Run in ASP.NET Core middleware.


Q.What is the difference between services.AddTransient and service.AddScope methods are
Asp.Net Core?

Ans:ASP.NET Core out of the box supports dependency injection. These 3 methods allows to
register the dependency. However, they offers different lifetime for registered service. Transient
objects are created for every request (when requested). This lifetime works best for lightweight,
stateless services. Scoped objects are the same within a request, but different across different
requests. Singleton objects created the first time they’re requested (or when
ConfigureServices is run and an instance is specified with the service registration).

Q.What is Kestral?

Ans: Kestrel is a cross-platform web server for ASP.NET Core based on libuv, a cross-platform
asynchronous I/O library. Kestrel is the web server that is included by default in ASP.NET Core
new project templates. If your application accepts requests only from an internal network, you
can use Kestrel by itself.

If you expose your application to the Internet, you must use IIS, Nginx, or Apache as a reverse
proxy server. A reverse proxy server receives HTTP requests from the Internet and forwards
them to Kestrel after some preliminary handling. The most important reason for using a reverse
proxy for edge deployments (exposed to traffic from the Internet) is security. Kestrel is relatively
new and does not yet have a full complement of defenses against attacks.

Q.What is WebListener?

Ans: ASP.NET Core ships two server implementations Kestral and WebListener. WebListener
is also a web server for ASP.NET Core that runs only on Windows. It’s built on the Http.Sys
kernel mode driver. WebListener is an alternative to Kestrel that can be used for direct
connection to the Internet without relying on IIS as a reverse proxy server.

Q.What is ASP.NET Core Module (ANCM)?

Ans: ASP.NET Core Module (ANCM) lets you run ASP.NET Core applications behind IIS and
it works only with Kestrel; it isn’t compatible with WebListener. ANCM is a native IIS module
that hooks into the IIS pipeline and redirects traffic to the backend ASP.NET Core application.
ASP.NET Core applications run in a process separate from the IIS worker process, ANCM also
does process management. ANCM starts the process for the ASP.NET Core application when the
first request comes in and restarts it when it crashes. In short, it sits in IIS and routes the request
for ASP.NET Core application to Kestral.

Q.What are different ASP.NET Core diagnostic middleware and how to do error handling?

Ans: Read Various ASP.NET Core Diagnostics Middleware.


Q.What is a Host and what’s the importance of Host in ASP.NET Core application?

Ans: ASP.NET Core apps require a host in which to execute. The host is responsible for
application startup and lifetime management. Other responsibility of host’s includes ensuring the
application’s services and the server are available and properly configured. Don’t confuse
yourself with a Server. The host is responsible for starting the app and its management, where
the server is responsible for accepting HTTP requests. The host is configured to use a particular
server; the server is unaware of its host.

The host is typically created using an instance of a WebHostBuilder, which builds and returns a
WebHost instance. The WebHost references the server that will handle requests.

public class Program

public static void Main(string[] args)

var host = new WebHostBuilder()

.UseKestrel()

.UseContentRoot(Directory.GetCurrentDirectory())

.UseIISIntegration()

.UseStartup<Startup>()

.Build();

host.Run();

view raw netcore1.1_program.cs hosted with by GitHub

In ASP.NET Core 2.0, it is changed. It looks like this:


public class Program

public static void Main(string[] args)

BuildWebHost(args).Run();

public static IWebHost BuildWebHost(string[] args) =>

WebHost.CreateDefaultBuilder(args)

.UseStartup<Startup>()

.Build();

view raw netcore2.0_program.cs hosted with by GitHub

Read this post to know more.

Q. What does WebHost.CreateDefaultBuilder() do?

Ans: This method does the following things.

 Configure the app to use Kestrel as web server.


 Specify to use the current project directory as root directory for the application.
 Setup the configuration sub‐system to read setting from appsettings.json and
appsettings.{env}.json to environment specific configuration.
 Set Local user secrets storage only for the development environment.
 Configure environment variables to allow for server‐specific settings.
 Configure command line arguments (if any).
 Configure logging to read from the Logging section of the appsettings.json file and log to the
Console and Debug window.
 Configure integration with IIS
 Configure the default service provider.
You can take a look at the code of this method here.

Q.What is the role of IHostingEnvironment interface in ASP.NET Core?

Ans: ASP.NET Core offers an interface named IHostingEnvironment, allows you to


programmatically retrieve the current environment so you can have an environment-specific
behaviour. By default, ASP.NET Core has 3 environments Development, Staging, and
Production. Previously, the developers have to build the application differently for each
environment (Staging, UAT, Production) due to dependency on config file sections and the
preprocessor directive applicable at compile time. ASP.NET Core takes a different approach and
uses IHostingEnvironment to retrieve the current environment. You can also define a custom
environment like QA or UAT.

Q.How to handle 404 error in ASP.NET Core 1.0?

Ans: Read How to handle 404 error in ASP.NET Core 1.0

Q.What is the use of UseIISIntegration?

Ans: This tells ASP.NET that IIS will be working as a reverse proxy in front of Kestrel. As if
you expose your application to the Internet, you must use IIS, Nginx, or Apache as a reverse
proxy server. When you wish to deploy your ASP.NET Core application on windows, you need
to tell ASP.NET Core Host to use IIS integration.
UseKestrel and UseIISIntegration must be used in conjunction as UseKestrel creates the
web server and hosts the code. UseIISIntegration specifies IIS as the reverse proxy server.

1var host = new WebHostBuilder()

2 .UseKestrel()

3 .UseContentRoot(Directory.GetCurrentDirectory())

4 .UseIISIntegration()

5 .UseStartup<Startup>()

.Build();
6

Note that code making call to UseIISIntegration() does not affect code portability.

Q.What are the different ways for bundling and minification in ASP.NET Core?

Ans: There are different ways for doing bundling and minification in ASP.NET Core.

 Gulp – was the default choice for ASP.NET Core till beta versions. Later it was removed due to
performance and speed issue and replaced with BundlerMinifier. Read this post to find out the
reasons of this decision.
 BundlerMinifier – is a Visual Studio extension and it’s default choice now. You should see
bundleconfig.json file in your default template. Read this post to know more about bundling and
minification in ASP.NET Core.
 ASP.NET Core Web Optimizer – ASP.NET Core middleware for bundling and minification of CSS
and JavaScript files at runtime.
 Grunt – can also be used with ASP.NET Core.

For more Read Overview of Tools for bundling and minification in ASP.NET Core.

Q.What is launchsetting.json in ASP.NET Core?

Ans: Read Launchsetting.json in ASP.NET Core

Q.What is wwwroot folder in ASP.NET Core?

Ans: In ASP.NET Core, all the static resources, such as CSS, JavaScript, and image files are
kept under the wwwroot folder (default). You can also change the name of this folder.

Q.What is “Razor pages” in ASP.NET Core?

Ans: “Razor Pages” is a new feature of ASP.NET Core and it was released with ASP.NET Core
2.0 release. Razor Pages are simple pages or views without controllers and introduced with the
intent of creating page focused scenarios where there is no real logic is involved. You will find
razor pages similar to ASP.NET Web Forms. They work on the convention and need to be
placed in Pages folder and the extension is .cshtml. Razor pages uses handler methods to deal
with incoming HTTP request. Read this post to find out more about handler methods.

Q.What is tag helper in ASP.NET Core?

Ans: Tag Helpers enable server-side code to participate in creating and rendering HTML
elements in Razor files. For example, the built-in ImageTagHelper can append a version number
to the image name. There are many built-in tag helpers like From, Image, Anchor and many
others. Read How to use image tag helper in ASP.NET Core and How to use select tag helper in
ASP.NET Core. Read more about Tag Helpers @ official documentation.

You might also like