Asp.net Core Interview Question Part 3

What is Db Context in .NET Core?

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

For example, I have created a My App DB Context class which looks like this –

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

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.

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!");
            });

Asp.net Core Interview Question

What is Configure Services() in .NET Core?

Configure Services() 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>();
}

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().

Syntax to add a middleware inside Configure() method.

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

What is Service Lifecycle?

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

Add Transient()
Add Singleton()
Adds coped()

Advance Asp.net Core Interview Question

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 CoreFx?

CoreFx is the reimplementation of the class libraries for .NET Core.

Differences Between .NET Core and .NET Framework?

The differences between the two can be summarized in these three points:

NuGet-based: .NET Core is distributed as a set of NuGet packages that allow app-local deployments. In contrast, the .NET-Framework is always installed in a system-wide location. This difference doesn’t matter so much for class libraries, but it matters for applications as those are expected to deploy the closure of their dependencies. But we expect this model to change how quickly class library authors can take advantage of new functionality. Since the applications can simply deploy a new version (as opposed to having to wait until a given .NET Framework version is widely adopted), there is less of a penalty for component authors to take advantage of the latest features.

Well layered: .NET Core was specifically designed to be layered. The goal was to create a .NET stack that can accommodate a wide variety of capabilities and system constraints without forcing customers to recompile their binaries and/or produce new assets. This means that we had to remove certain APIs because they tied lower-level components to higher-level components. In those cases, we provide alternatives, often in the form of extension methods.

Free of problematic tech: .NET Core doesn’t include certain technologies we decided to discontinue because we found them to be problematic, for instance, App Domain and sandboxing. If the scenario still makes sense for .NET Core, our plan is to have replacements. For example, Assembly Load Context replaces App Domains for loading and isolating assemblies.

Asp.net Core Interview Question

What are Generate SQL scripts in .NET core?

When debugging your migrations or deploying them to a production database, it’s useful to generate a SQL script. The script can then be further reviewed for accuracy and tuned to fit the needs of a production database. The script can also be used in conjunction with a deployment technology.

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. Thread Pool 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 Thread Pool, a task does not create its own OS thread. Instead, tasks are executed by a Task Scheduler; the default scheduler simply runs on the Thread Pool. Unlike the Thread Pool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result.

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.

Advance Asp.net Core Interview Question

What is a delegate in .NET?

A delegate in .NET is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. In addition, we could use delegate to create custom event within a class.

What is UWP App in .NET core?

UWP apps will be able to use libraries you have created in .NET core as long as you target the .netstandard1.6 (or higher) framework moniker. UWP is only for the Windows ecosystem.

What is MS Build and how it works with .NET Core?

MSBuild is the build platform for Microsoft and Visual Studio. In the UWP application if you open the project folder, then you will see both project.json and *.csproj files. But if you open our previous .NET Core Console app, then you will see project.json and *.xproj files.

Asp.net Core Interview Question

What are Razor Pages in .NET Core?

Razor Pages is a new server-side framework which works on a page-based approach to render applications in .NET Core. They are stored as a physical .cshtml file.

They have the HTML and code in a single file, without the need to maintain separate controllers, view models, action methods, etc. We can also have the code separate from the HTML in a different file which is attached to the Razor Page.

Razor Pages framework is flexible, lightweight, cohesive, page-based, easy to learn and maintain compared to MVC. It can be used in conjunction with traditional MVC (Model-View-Controller) architecture or Web-API controllers.

What are service lifetimes in .NET Core?

.NET Core supports a design pattern called ‘Dependency Injection’ which helps in the implementation of IoC(Inversion of Control). During registration, dependencies require their lifetime to be defined. The lifetime of service decides under what condition the instance of the service will be created and till what time it will be live.

There are three types of service lifetimes supported by .NET Core:

Transient Service: Instance is created each time it is requested.
Scoped Service: User-specific instance is created once per user and shared across all the requests.
Singleton Service: Single Instance is created once a lifetime of the application.
Service Lifetime in .NET Core

What is response caching in .NET Core?

During response caching, cache-related headers are mentioned in the HTTP responses of .NET Core MVC actions. Using these headers, we can specify how the client/proxy machine will cache responses to requests. This, in turn, reduces the number of client/proxy requests to the web server because the responses are sent from the cache itself.

As we can see in the below diagram, the first request has a complete cycle from client browser to proxy server and then subsequently to web server. Now, the proxy server has stored the response in the cache. For all the subsequent requests, the proxy server sends the response from the cache itself. Hence, the number of proxy/client requests to the web server is reduced.

Advance Asp.net Core Interview Question

What is a generic host in .NET Core?

The generic host was previously present as ‘Web Host’, in .NET Core for web applications. Later, the ‘Web Host’ was deprecated and a generic host was introduced to cater to the web, Windows, Linux, and console applications.

Whenever a new application is started we are required to take care of the below points:

Dependency Injection
Configuration
Logging
Service lifetime management
.NET generic host called ‘Host Builder’ helps us to manage all the above tasks since it is built on the original abstraction of these tools.

What is .NET Standard?

.NET Standard is a set of APIs that all .NET platforms have to implement. This unifies the .NET platforms and prevents future fragmentation.
.NET Standard 2.0 is implemented by .NET Framework, .NET Core, and Xamarin. For .NET Core, this added many of the existing APIs that have been requested.
.NET Standard 2.0 includes a compatibility shim for .NET Framework binaries, significantly increasing the set of libraries that you can reference from your .NET Standard libraries.
.NET Standard will replace Portable Class Libraries (PCLs) as the tooling story for building multi-platform .NET libraries.

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

Asp.net Core Interview Question

Explain startup process in ASP.NET Core?

Everything starts from Program.cs


public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}
 
public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();

Create Default Builder extension method will create a default configuration which will look first into appsettings.json files then will look for Environment variables and at the end, it will use command line arguments.

This part will also set up default logger sources (debug and console) and load the settings for logging from appsettings.json.

After the Create Default Builder finishes, then Startup class is executed. First, the constructor code is executed. After that, services are added to DI container via Add Services method that lives in Startup class. After that, an order of middleware that will handle every incoming request is set up.

What is new in ASP.NET Core 2, compared to ASP.NET Core 1?

With ASP.NET Core 2 several new features came out:

Razor Pages
Db Context Pooling with Entity Framework Core 2
Simplified Application Host Configuration
Configuration is now part of DI and ready for the time server reaches Startup class
Simplified authentication model
dotnet new now restore NuGet packages automatically
New meta package – Microsoft.AspNetCore.All

What about static files in ASP.NET Core (MVC)?

All static files are now (by default) located inside of www.root folder. You store your CSS, JS, images, fonts and others static content inside of it.

Advance Asp.net Core Interview Question

Do you see .NET Core demand growing in the next few years?

This question can give an interviewer insight into how well-informed you are about upcoming technology and industry news. Often the accuracy of your answer is less important than the passion and interest you show. Consider giving an honest answer that showcases your technical and industry knowledge.

Example: “.NET Core has many features I think make it one of the best server-side web frameworks, and it is growing in popularity. I am excited to see how it keeps developing and what software development opportunities come from using .NET Core.”

How do you explain what a service lifetime is?

“A service lifetime refers to how long an object lives after being created. The three typical lifetimes are transient, scoped and singleton. Transient lifetimes are ideal for stateless and lightweight services because they get created each time the service container gets used. Scoped lifetimes happen once every connection. Singleton lifetimes happen when initially created and again with each subsequent request from the service container.”

What are some challenges you face while working with .NET Core?

When I first became familiar with .NET Core, I often experienced server overloads and database issues when developing an application for my primary client. I noticed the landing pages worked, though they performed slowly with a lag time that might deter users. I connected with database administrators to monitor settings that allowed us to gain better performance while we further developed the app.”

Asp.net Core Interview Question

What is an action method?

“An action method executes activity when an HTTP request takes place. It is a controller class that has specific parameters. For example, action method must be public, rather than protected or private. It cannot get overloaded and it cannot be a static method.”

What are caching and response caching in .NET Core?

“Caching is a process that reduces the number of calls to the data source, improving the application’s performance and scalability. It essentially stores a copy of the data instead of generating it each time you access the original source. For example, if you visit a specific website or app frequently, some data already on your device let the page run faster, giving you a better user experience. For data that frequently changes, response caching sets parameters for the headers that control caching.”

What is IWebHost interface in ASP.NET Core?

IWebHost is one of the building block of ASP.NETCore , It contains application configuration and kestrel server.

Advance Asp.net Core Interview Question

What is the difference between Program class and Startup class?

-Program class is used to define required infrastructure to an application like Application settings , Logging and Web Server related etc..
-Program class required changes rarely.

-Startup class is used to define application components and features etc.
-Startup class required changes frequently.

What is Configure Services and Configure methods in Startup class in ASP.NET Core?

-Configure Services method is used to registering the service with IServiceCollection
-Configure method is used to configure the middleware pipeline for handling HTTP requests.

Services those are configured in Configure Services methods those are available to Configure methods

public class Startup
{
Public void ConfigureServices(IServiceCollection service)
{
//here registering the service with IServiceCollection.
}
Public void Configure(IApplicationBuilder ap)
{
//here configure the middleware pipeline for handling HTTP requests.
}
}

What is Web Server used in ASP.NET Core?

By default ASP.NET Core using Kestrel webserver.

Asp.net Core Interview Question

What is ASP.NET Core application life cycle?

All clients requests goes to web server (IIS/Apache/Ngix etc.), from web server to ASP.NET Core Server that is either Kestrel or other , From here to application middle ware, Here requests are handled and response generated , this response transferred to client vice versa to request.

What is HTTP Context object in ASP.NET Core?

HTTP Context object created by ASP.NET Core webserver , Its contains the information about request specific services , configuration details, data loads and errors information and it is passes to entire application.

What is middleware pipeline in ASP.NET Core?.

In ASP .NET Core middleware is .NET class handle HTTP request or response.

It is responsible to transfer request or response to the set of components that is execute in a sequence order.

In Startup class Configure method is used to define middleware.

In middleware components order is important , In given order only components execution will be done.

Middleware able to call another and this middleware calls another middleware and so on. This is called pipeline.

Advance Asp.net Core Interview Question

What is difference between HTTP handler , HTTP modules and ASP.NET Core Middleware?

HTTP handler process the request and send response back to browser.
HTTP modules handle the requests based events, but should have complete understanding on request state.
.NET Core middleware pipeline request transferred between different middleware’s generate response. Pipeline is define in code so that we have control over request transition. you can change order whenever you want.

Why Exception Handler middleware place in the first in ASP.NET Core?

-ASP.NETCore middleware pipeline is always bidirectional.
-Request first enter into the Exception Handler middleware, While entering it is almost ignored , but while sending the response it is the last middleware so that If response contains any errors, modify the response and send a friendly message back to the client or re execute pipeline again.
-If Exception Handler not handling the errors webserver returns a status codes to the user.

What is the error handling namespaces in ASP.NETCore?

Microsoft.AspNetCore.All
Microsoft.AspNetCore.Diagnostics

Asp.net Core Interview Question

What is the app.UseDeveloperExceptionPage() middleware in ASP.NETCore?

-If we want to get full information about exceptions(Line number + Exception information+request that caused + Fullstack trace) while developing the application you can use this middleware.
-This middleware using DeveloperExceptionPageMiddleware class.

What is the app.UseStatusCodePages() middleware in ASP.NETCore?.

Using this middleware you can get different response for different status codes.

How can we disable middleware in ASP.NETCore?

Using HTTP Context class Features property.

Example:

Public void SCode()
{
var sCodeFeature = HttpContext.Features<IStatusCodePagesFeatures>();
if(sCodeFeature != null)
{
sCodeFeature.Enabled = false;
}
}

Advance Asp.net Core Interview Question

How to add middleware in ASP.NET Core applications?

In two ways we are adding this
1)Using nuget package manager.
2)By editing project file.

Where we define Route in ASP.NETCore?

Define route in Startup class configure method.

What is Tag Helpers in ASP.NETCore ?

-Using TagHelpers able to render server side code in HTML elements in Razor files.
-Different kind of Tag Helpers available for different purposes.

Example:

Anchor TagHelper , Environment TagHelper Etc.
<label asp-for="College.DeptName"></label>

Asp.net Core Interview Question

What is Form Tag Helper in ASP.NETCore?

FormTagHelper used to generate action attribute depends given data.
-By default predominately generating hidden field for preventing CSRF attacks.

CSRF token name is like “_RequestVerificationToken”

For above syntax generating action attribute like GetData/GetTransport/5

What is Cache busting?

-Caching is mechanism used to increase performance an application.

-With caching , all browsers cache files locally and reuse them for subsequent requests

-Caching good idea , If an application has static content and not changed frequently, in case application has frequent changes then it will create an issue.

“Cache busting solve the browser caching issue if your application has frequent changes”

-To avoid above issue appending parameter in URL like ?v=1 , browser caching the based on URL, If application changes needs to query parameter ?v=2 again changing parameter for every change in application needs to manual intervention and time taking processes

How Cache busting handled in ASP.NETCore?

  • Using app-append-version = ‘true’ attribute you can handle cache busting in ASP.NETCore.
  • app-append-version attribute generate a unique hashcode will be generated for the server side resources , If resource got changed new hash code will be generated so that query string also getting changed
    -Depends on hashcode browser handle the requests and responses.
    -You can apply this attribute to

Advance Asp.net Core Interview Question

What is Ok() helper method in ASP.NETCore?

-Ok helper method return 200 status code.
-This status code return when requested data found.
-If you want you can return the data,

What is Not Found() helper method in ASP.NETCore?

-Not Found helper method return 404 status code.
-This status code return when requested data not found.

Asp.net Core Part 1Asp.net Core Part 2
Back to top