0% found this document useful (0 votes)
51 views9 pages

Core

.Net Core --- BASIC QUESTIONS and ANSWERS 1)What are the benefits of using ASP.NET Core over ASP.NET? ASP.NET Core is a high-performance, cross-platform, and open-source framework. It allows you to build modern, cloud-enabled, and Internet-connected apps. 2)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
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views9 pages

Core

.Net Core --- BASIC QUESTIONS and ANSWERS 1)What are the benefits of using ASP.NET Core over ASP.NET? ASP.NET Core is a high-performance, cross-platform, and open-source framework. It allows you to build modern, cloud-enabled, and Internet-connected apps. 2)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
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

.

Net Core --- BASIC QUESTIONS and ANSWERS

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

ASP.NET Core is a high-performance, cross-platform, and open-source framework. It


allows you to build modern, cloud-enabled, and Internet-connected apps.

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

3) Describe the Dependency Injection.

Dependency Injection (DI) is a design pattern used in object-oriented programming


(OOP) that involves creating objects with their dependencies, rather than having them
create their own dependencies. In other words, rather than having an object create its
dependencies internally, the dependencies are "injected" from outside the object

There are different ways of injecting the dependency (DI) - Constructor Dependency
Injection, Interface Dependency Injection, Method Parameter Dependency Injection, and
Setter Property Dependency Injection.

4) Explain the difference between app.Run and app.Use in ASP.NET Core.

app.Use method adds a middleware delegate to the application's request pipeline.


When you want to pass the context to the next middleware then prefer app.Use
method.

app.Run method adds a terminal middleware delegate to the application's request


pipeline. When you want to terminate the pipeline then prefer to use the app.Run
method.

5) Explain the Middleware in ASP.NET Core.

Middleware in ASP.NET Core is a powerful tool that allows you to add modular and
reusable components to your application's request/response pipeline. By using
middleware, you can handle cross-cutting concerns in a centralized and flexible way,
making it easier to maintain and extend your application over time
.Net Core --- Advanced QUESTIONS and ANSWERS

What is the difference between app.Run and app.Use in ASP.NET Core.

 app.Use method adds a middleware delegate to the application's request pipeline.


When you want to pass the context to the next middleware then prefer app.Use
method.
 app.Run method adds a terminal middleware delegate to the application's request
pipeline. When you want to terminate the pipeline then prefer to use the app.Run
method.

app.Use((context, nextMidWare) => { context.Response.Body.Write("Hello app.Use");


nextMidWare(context);});

app.Run((context) => context.Response.Body.Write("Hello app.Run"));

app.Use((context, nextMidWare) => context.Response.Body.Write("Hello , again app.Use"));

Output:
Hello app.Use
Hello app.Run

What’s the difference between synchronous and asynchronous programming in


ASP.NET Core?

Synchronous programming in ASP.NET Core blocks the execution of source code until a task
is completed. In contrast, asynchronous programming allows the execution of code to
continue while a task is being processed in the background.

Asynchronous programming is useful for long-running operations that would otherwise block
the application's main thread, such as reading from a file or making a network request.

Asynchronous programming is typically achieved using the async and await keywords in C#.
The async keyword defines an asynchronous method, which can be called by other code and
will run in the background. The await keyword indicates that the calling code should wait for
the asynchronous method to complete before continuing.

How to read values from Appsettings.json file?

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’s the difference between middleware and a filter in ASP.NET Core?

ASP.NET Core, middleware and filters are two mechanisms used for processing requests and
responses.

Middleware is a software component between the web server (like Apache) and the
application and processes requests and responses during the application development.
Middleware can be used for various tasks, such as authentication, logging, and error
handling. Middleware is executed in a pipeline, and each middleware component can modify
the request or response before passing it to the next component in the pipeline.

Conversely, filters are used to perform cross-cutting concerns on controllers and actions in an
MVC application. Filters can be used for authorization, validation, and caching tasks. Filters
are executed before and after the action method, and they can modify the request or
response or short-circuit the request processing if necessary.

The main difference between middleware and filters is their scope and the way they are
executed. Middleware is executed globally and can be used for any request or response. In
contrast, filters are executed only for specific controllers or actions and can be used to modify
the request or response before or after the action method.

How can you implement background work in an ASP.NET Core application?


The IHostedService interface in ASP.NET Core defines a background task or service
as part of the application's lifetime. It’s typically used for monitoring, logging, or data
processing tasks that must run continuously, even when the application is not processing
requests. Classes that implement the IHostedService interface are added to the application's
service collection using dependency injection, and they are started and stopped automatically
by the application's host.

The IHostedService interface defines two methods: StartAsync and StopAsync. The
StartAsync method is called when the application starts and is used to start the background
task or service. The StopAsync method is called when the application is stopped or restarted.
It’s used to stop the background task or service, releasing acquired resources.

How does ASP.NET Core handle dependency injection?

Dependency injection is a design pattern of ASP.NET Core that’s handled by the built-in
dependency injection container. This container can register and resolve dependencies,
typically defined as interfaces implemented by concrete classes.

There are several ways to configure the container, including the ConfigureServices method in
the Startup class (the entry point of a .NET application), attributes on classes and properties,
and the service provider itself. ASP.NET Core supports constructor, property, and method
injection, allowing dependencies to be dynamically injected into methods at runtime.

--> what problems does Dependency Injection solve?


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.

Dependency Injection example. A class can use a direct dependency instance as below.
Public class A {
MyDependency dep = new MyDependency();

public void Test(){


dep.SomeMethod();
}
}

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.

Explain the concept of dependency injection in .NET Core.


Dependency injection (DI) in .NET Core is a technique for achieving Inversion of Control (IoC)
between classes and their dependencies. It promotes loose coupling, testability, and
maintainability by allowing the runtime to provide required dependencies instead of
hardcoding them within classes.
.NET Core’s built-in DI container differs from other frameworks like Autofac or Ninject in its
simplicity and lightweight nature. While it provides basic features such as constructor,
property, and method injection, it lacks advanced capabilities like interception or auto-
registration. However, it can be easily replaced with third-party containers if needed.
In .NET Core, services are registered in the ConfigureServices method of the Startup class
using IServiceCollection extension methods like AddTransient, AddScoped, and
AddSingleton. These methods define the lifetime of the service instances.

How do you secure your .NET Core applications? What is the different authentication
and authorization mechanisms available.
To secure .NET Core applications, implement authentication and authorization mechanisms.
Authentication verifies user identity, while authorization determines access rights.
1. Cookie-based: Use ASP.NET Core Identity for storing user information and managing
authentication via cookies.
2. Token-based: Utilize JSON Web Tokens (JWT) to authenticate users without server-
side sessions.
3. OAuth 2.0/OpenID Connect: Integrate with external providers like Google or
Facebook using these protocols.
4. Windows Authentication: Employ this mechanism in intranet scenarios where Active
Directory is available.
5. Certificate Authentication: Authenticate clients based on X.509 certificates, suitable
for mutual TLS scenarios.
For authorization:
1. Role-based: Grant access based on predefined roles assigned to users.
2. Claims-based: Evaluate claims within a user’s identity to determine permissions.
3. Policy-based: Define custom policies with specific requirements, evaluated by the
Authorization Middleware.

How do you implement exception handling and logging in .NET Core applications?
In .NET Core applications, exception handling and logging are implemented using middleware
components. Middleware is a chain of components that handle requests and responses in the
application pipeline.
For exception handling, use the built-in “UseExceptionHandler” middleware to catch
exceptions and provide custom error pages or responses. Configure it in the “Startup.cs” file
within the “Configure” method:

app.UseExceptionHandler(options =>
{
options.Run(async context =>
{
// Custom error response logic here
});
});

For logging, utilize the ILogger interface provided by Microsoft.Extensions.Logging


namespace. Inject ILogger into classes via dependency injection:
public class MyClass

private readonly ILogger _logger;

public MyClass(ILogger logger)

_logger = logger;

What is meant by state management?


state management is a kind of state control object to control the states of the object during
different processes. Since stateless protocol, HTTP has been used, which is unable to retain
user values; thus, different methods have been used to store and preserve the user data
between requests.
Approach Name Storage Mechanism
Cookies HTTP Cookies, Server-side app code
Session state HTTP Cookies, Server-side app code
Temp Data HTTP Cookies, Session State
Query Strings HTTP Query Strings
Hidden Fields HTTP Form Fields
HTTPContext.Items Server-side app code
Cache Server-side app code

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

What are the various ways to manage errors in .NET Core for web APIs?
There are mainly four ways to manage errors in .NET Core for web APIs.
1. Developer Exception Page
2. Exception Handler Page
3. Exception Handle Lambda
4. UseStatusCodePages
If you compare these four methods, the best way is "Developer Exception Page" as it
provides detailed information (stacks, query string parameters, headers, cookies) about
unhandled request exceptions. You can easily enable this page by running your applications
in the development environment. This page runs early in the middleware pipeline, so you can
easily catch the exception in middleware.

Model Validation.
Model Validation in ASP.NET Core is the process of ensuring that the data submitted by the
user meets certain rules and constraints before processing it further. It helps to maintain data
integrity and prevent invalid or malicious data from being processed by the application.
ASP.NET Core provides built-in support for model validation using data annotations. These
annotations are applied to the properties of the model class, and they define the validation
rules that should be enforced. For example, the [Required] attribute specifies that a property
must have a non-null value, and the [StringLength] attribute sets the minimum and maximum
length for a string property.
When a request is made, ASP.NET Core automatically validates the model based on the
defined validation rules. If any validation errors occur, they are added to the ModelState
object, which can be accessed and displayed to the user.

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 your understanding of SOLID principles?


The SOLID principles are a set of guidelines for writing clean, maintainable, and extensible
object-oriented code:
Single Responsibility Principle (SRP): A class should have only one reason to change.
Open/Closed Principle (OCP): Software entities (classes, modules, functions, etc.) should be
open for extension but closed for modification.

Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types.

<="" strong="" style="box-sizing: border-box;">Clients should not be forced to depend on


interfaces they do not use.

Dependency Inversion Principle (DIP): High-level modules should not depend on low-level
modules. Both should depend on abstractions.

Adhering to the SOLID principles helps create modular, flexible, and maintainable code that is
easier to understand, test, and extend over time.

How does the Garbage Collector work?


The Garbage Collector (GC) is a key component of the .NET runtime. GC automatically
manages the allocation and deallocation of memory for managed objects on the heap.
Garbage Collector works by periodically scanning the managed heap and identifying objects
that are no longer reachable, and reclaiming the memory occupied by those objects.
Here’s a general overview of how the Garbage Collector works:

Marking Phase: During this phase, the GC identifies the root objects (objects that are
currently in use, such as static objects, objects on the stack, and objects referenced by CPU
registers). It then traverses all references from these root objects, marking all reachable
objects as "live."

Marking Phase Ending: After marking all live objects, the GC checks for sufficient memory to
continue execution. If not, it proceeds to the next phase.

Relocating Phase: In this phase, the GC compacts the heap by moving all live objects to one
end of the heap, creating a contiguous block of free memory.

Reclaiming Phase: After compacting the heap, the GC reclaims the memory occupied by
unreachable (dead) objects, making it available for future allocations.

The GC employs various techniques and algorithms to optimize its performance. These
techniques include generational garbage collection, which divides the heap into generations
based on object lifetime, and background garbage collection, which allows the GC to run
concurrently with the application’s threads.

a web server performs a database query for an HTTP request. The server has 16
threads in total. Each HTTP request executes a database query and waits for the
results, blocking the thread. Can this be optimized using .NET means?
This scenario can be optimized using asynchronous programming in .NET. Instead of
blocking threads waiting for database queries, use async/await with asynchronous database
operations, allowing threads to be released back to the thread pool while waiting. Also,
consider increasing the maximum thread pool size if expecting high concurrency.
What is loosely-coupled code? How is it better than tightly-coupled code? How would
you achieve loose coupling?
Loosely-coupled code has minimal dependencies between components, enabling
independent development and evolution. It’s better than tightly-coupled code, which is harder
to maintain and change. Achieve loose coupling through abstractions (interfaces),
dependency injection, event-driven communication, and modular design.

Does using static classes increase or decrease code coupling?


Static classes can increase code coupling by introducing global states and dependencies
across the codebase. Static classes are best used judiciously for utility classes or when truly
required.

Generic and non-generic


-----------------------------------------------
how generic is faster in performance while compare with non generic
collections ?
Generic collections typically perform better than non-generic collections
for storing and manipulating value types because they don't require
boxing the elements. Here's how generic collections improve
performance:
 Compile-time resolution
Generic types are resolved at compile-time, eliminating the need for
boxing and unboxing operations.
 Strong typing
Generic collections are strongly typed and don't need type casting,
making them less error-prone.
 Compiler optimization
Specifying data types upfront allows the compiler to optimize the code,
resulting in faster execution.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy