Developer's Guide to C# & ASP.NET
Developer's Guide to C# & ASP.NET
Contents
Data Structures and Algorithm .............................................................................................................................................. 3
Data Structures: .................................................................................................................................................................. 3
Classification/Types of Data Structures: ............................................................................................................................. 3
Most Popular Data Structures: ........................................................................................................................................... 4
❖ Array: ...................................................................................................................................................................... 4
❖ Linked Lists: ............................................................................................................................................................ 4
❖ Stack:....................................................................................................................................................................... 4
❖ Queue: .................................................................................................................................................................... 5
❖ Matrix: .................................................................................................................................................................... 5
Data Types:.......................................................................................................................................................................... 7
❖ LIFO - Last In, First Out: .............................................................................................................................................. 7
❖ FIFO - First In, First Out: ............................................................................................................................................. 8
Algorithms: .......................................................................................................................................................................... 9
Fibonacci Series – Algorithm: ......................................................................................................................................... 9
Sample Q&A: ....................................................................................................................................................................... 9
Object Oriented Programming – C# ..................................................................................................................................... 11
Sample Questionnaires on Object Oriented Programming – C# ...................................................................................... 28
C# - Design Pattern (For Advanced) ..................................................................................................................................... 36
Sample Questionnaires on Design Pattern in C#: ............................................................................................................. 38
ASP.NET ................................................................................................................................................................................ 39
ASP.NET Web Forms Model .............................................................................................................................................. 39
The ASP.NET Component Model ...................................................................................................................................... 39
Components of .Net Framework ...................................................................................................................................... 40
ASP.NET Application Life Cycle ......................................................................................................................................... 41
ASP.NET Page Life Cycle .................................................................................................................................................... 41
ASP.NET Page Life Cycle Events ........................................................................................................................................ 42
ASP.NET - Event Handling ................................................................................................................................................. 42
ASP.NET - Data Sources..................................................................................................................................................... 44
Sample Questionnaires on ASP.NET: ................................................................................................................................ 45
ASP.NET (MVC) ..................................................................................................................................................................... 48
Overview: Definition ......................................................................................................................................................... 48
ASP.NET MVC Folder Structure: ........................................................................................................................................ 50
Routing in MVC: ................................................................................................................................................................ 52
1
RESTRICTED
RESTRICTED
Configure a Route:........................................................................................................................................................ 52
ASP.NET MVC- Filters: ....................................................................................................................................................... 53
ASP.NET MVC – Scaffolding: ............................................................................................................................................. 54
Sample Questionnaires on ASP.NET (MVC): ..................................................................................................................... 54
ASP.NET Core ........................................................................................................................................................................ 57
Overview: Definition ......................................................................................................................................................... 57
ASP.NET Core - Project Structure: ..................................................................................................................................... 57
Sample Questionnaires on ASP.NET Core: ........................................................................................................................ 64
ASP.NET Core - Authorization & Authentication................................................................................................................. 78
Sample Questionnaires on ASP.NET Core - Authorization & Authentication ................................................................ 79
ASP.NET Core – Configuration ............................................................................................................................................. 80
Sample Questionnaires on ASP.NET Core – Configuration: .............................................................................................. 81
ASP.NET Core - Logging and Monitoring ............................................................................................................................. 83
Sample Questionnaires on ASP.NET Core - Logging and Monitoring: .............................................................................. 84
ASP.NET Core - Middleware ................................................................................................................................................. 86
Sample Questionnaires on ASP.NET Core Middleware: ................................................................................................... 90
ASP.NET Core - Host ............................................................................................................................................................. 92
Sample Questionnaires on ASP.NET Core – HOST: ........................................................................................................... 92
ASP.NET – Worker Service & Background Service .............................................................................................................. 94
Sample Questionnaires on Worker Service & Background Service: ............................................................................... 95
ASP.NET Core - Globalization & Localization ....................................................................................................................... 96
Sample Questionnaires on ASP.NET Core – Globalization & Localization: ....................................................................... 97
ASP.NET Core - SignalR ......................................................................................................................................................... 97
Sample Questionnaires on ASP.NET Core – SignalR: ...................................................................................................... 99
Sample Questionnaires on ASP.NET Core - WEB API: ....................................................................................................... 100
Sample Questionnaires on HTML: ..................................................................................................................................... 103
Sample Questionnaires on CSS: ......................................................................................................................................... 106
Sample Questionnaires on Javascript: ............................................................................................................................... 109
Sample Questionnaires on jQuery: .................................................................................................................................... 114
2
RESTRICTED
RESTRICTED
Information:
Information refers to processed or organized data that has been given context, meaning, and relevance. It results from
interpreting and analyzing data to extract insights, patterns, and relationships. Information provides a deeper
understanding and allows individuals to make informed decisions or draw conclusions.
Data Structures:
A data structure is a specialized format for organizing, processing, retrieving and storing data. There are several basic
and advanced types of data structures, all designed to arrange data to suit a specific purpose.
3
RESTRICTED
RESTRICTED
❖ Array:
An array is a collection of data items stored at contiguous memory locations. The idea is to store multiple items
of the same type together. This makes it easier to calculate the position of each element by simply adding an
offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name
of the array).
❖ Linked Lists:
Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at a contiguous
location; the elements are linked using pointers.
❖ Stack:
Stack is a linear data structure which follows a particular order in which the operations are performed. The order
may be LIFO(Last In First Out) or FILO(First In Last Out). In stack, all insertion and deletion are permitted at only
one end of the list.
4
RESTRICTED
RESTRICTED
❖ Queue:
Like Stack, Queue is a linear structure which follows a particular order in which the operations are performed.
The order is First In First Out (FIFO). In the queue, items are inserted at one end and deleted from the other end.
A good example of the queue is any queue of consumers for a resource where the consumer that came first is
served first. The difference between stacks and queues is in removing. In a stack we remove the item the most
recently added; in a queue, we remove the item the least recently added.
❖ Matrix:
A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose
the elements of a matrix in parentheses or brackets.
5
RESTRICTED
RESTRICTED
Stacks Queues
Insert operation is called push operation. Insert operation is called enqueue operation.
Stacks are implemented using an array or linked Queues are implemented using an array or linked list data
list data structure. structure.
Delete operation is called pop operation. Delete operation is called dequeue operation.
An array is a grouping of data elements of A linked list is a group of entities called a node. The node
equivalent data type. includes two segments: data and address.
It stores the data elements in a contiguous It stores elements randomly, or we can say anywhere in the
memory zone. memory zone.
In the case of an array, memory size is fixed, and it In the linked list, the placement of elements is allocated during
is not possible to change it during the run time. the run time.
The elements are not dependent on each other. The data elements are dependent on each other.
The memory is assigned at compile time. The memory is assigned at run time.
It is easier and faster to access the element in an In a linked list, the process of accessing elements takes more
array. time.
In the case of an array, memory utilization is In the case of the linked list, memory utilization is effective.
ineffective.
6
RESTRICTED
RESTRICTED
When it comes to executing any operation like When it comes to executing any operation like insertion,
insertion, deletion, array takes more time. deletion, the linked list takes less time.
✓ Operating system
✓ Graphics
✓ Computer Design
✓ Blockchain
✓ Genetics
✓ Image Processing
✓ Simulation
Data Types:
If data structures are the building blocks of algorithms and computer programs, the primitive -- or base -- data types are
the building blocks of data structures. The typical base data types include the following:
✓ Boolean: which stores logical values that are either true or false.
✓ Integer: which stores a range on mathematical integers -- or counting numbers. Different sized integers hold a
different range of values -- e.g., a signed 8-bit integer holds values from -128 to 127, and an unsigned long 32-bit
integer holds values from 0 to 4,294,967,295.
✓ Floating-point numbers: which store a formulaic representation of real numbers.
✓ Fixed-point numbers: which are used in some programming languages and hold real values but are managed as
digits to the left and the right of the decimal point.
✓ Character: which uses symbols from a defined mapping of integer values to symbols.
✓ Pointers: which are reference values that point to other values.
✓ String: which is an array of characters followed by a stop code -- usually a "0" value -- or is managed using a
length field that is an integer value.
Real-life example:
7
RESTRICTED
RESTRICTED
❖ FIFO vs LIFO:
FIFO LIFO
In this, the new element is inserted below the existing In this, the new element is inserted above the existing
element, So that the oldest element can be at the top element, So that the newest element can be at the top
and taken out first. and taken out first.
Therefore, the first element to be entered in this Therefore, the first element to be entered in this
approach, gets out First. approach, gets out Last.
Time complexity of inserting element in FIFO is O(1). Time complexity of inserting element in LIFO is O(1).
The data structure that implements FIFO is Queue. The data structure that implements LIFO is Stack.
Basic Terminology:
8
RESTRICTED
RESTRICTED
Algorithms:
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the
desired output. Algorithms are generally created independent of underlying languages, i.e. an algorithm can be
implemented in more than one programming language.
Algorithm for Iterative Fibonacci Series: The iterative approach is the dynamic programming approach. It makes use of a
loop to perform the addition of the previous two terms. The algorithm for the iterative approach will be:
Procedure Fibonacci(n)
declare f0, f1, fib, loop
set f0 to 0
set f1 to 1
for loop ← 1 to n
fib ← f0 + f1
f0 ← f1
f1 ← fib
<b>display fib</b>
end for
end procedure
Sample Q&A:
9
RESTRICTED
RESTRICTED
❖ What is a stack?
A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. Elements are added and
removed from the top of the stack. Common operations include push (add element) and pop (remove element).
10
RESTRICTED
RESTRICTED
11
RESTRICTED
RESTRICTED
}
C# Methods: A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also known as
functions.
Example: Create a method inside the Program class:
class Program
{
static void MyMethod()
{
// code to be executed
}
}
Class Members:
Fields and methods inside classes are often referred to as "Class Members":
Example: Create a Car class with three class members: two fields and one method.
// The class
class MyClass
{
// Class members
string color = "red"; // field
int maxSpeed = 200; // field
public void fullThrottle() // method
{
Console.WriteLine("The car is going as fast as it can!");
}
}
Constructors:
A constructor is a special method that is used to initialize objects. The advantage of a constructor, is that it is called when
an object of a class is created. It can be used to set initial values for fields:
Example:
Create a constructor:
// Create a Car class
class Car
{
public string model; // Create a field
// Create a class constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}
static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
12
RESTRICTED
RESTRICTED
}
// Outputs "Mustang"
Destructors:
Destructors in C# are methods inside the class used to destroy instances of that class when they are no longer needed.
✓ A Destructor is unique to its class i.e. there cannot be more than one destructor in a class.
✓ A Destructor has no return type and has exactly the same name as the class name (Including the same case).
Example:
class Example
{ // Destructor
~Example()
{
}
}
Access Modifiers:
Access modifiers are keywords used to specify the declared accessibility of a member or a type.
C# has the following access modifiers:
Modifier Description
protected The code is accessible within the same class, or in a class that is inherited from that class. You will
learn more about inheritance in a later chapter
internal The code is only accessible within its own assembly, but not from another assembly. You will learn
more about this in a later chapter
Example:
using System;
class BankAccount
{
public string AccountNumber { get; private set; } // Only accessible within the class
public decimal Balance { get; protected set; } // Accessible within the class and derived classes
internal string BankName { get; set; } // Accessible within the same assembly
protected internal string OwnerName { get; set; } // Accessible within the same assembly and derived classes
OwnerName = ownerName;
}
class Program
{
static void Main(string[] args)
{
BankAccount account = new BankAccount("123456789", 1000, "ABC Bank", "John Doe");
account.DisplayAccountInfo(); // Accessing public method
account.Balance = 1500; // Accessing protected set from within the class
account.BankName = "XYZ Bank"; // Accessing internal property within the same assembly
account.OwnerName = "Jane Smith"; // Accessing protected internal property within the same assembly
}
}
In this example:
✓ BankAccount class has properties with different access modifiers (private, protected, internal, protected internal).
✓ The Program class creates a BankAccount instance and accesses properties with different access levels.
Access modifiers provide control over the visibility and accessibility of class members, allowing you to enforce
encapsulation and control the interactions between classes.
C# Data Types:
In c# programming language, Data Types are useful to define a type of data the variable can hold, such as integer, float,
string, etc., in our application. Before we perform any operation on variables, it’s mandatory to define a variable with the
required data type to indicate what type of data that variable can hold in our application.
❖ Syntax of Defining C# Data Types:
• [Data Type] [Variable Name];
• [Data Type] [Variable Name] = [Value];
❖ Different Data Types in C#:
In C# programming language, we have a 3 different type of data types, those are
❖ Following is the example of using the data types in the c# programming language.
14
RESTRICTED
RESTRICTED
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int number = 10;
string name = "Suresh Dasari";
double percentage = 10.23;
char gender = 'M';
bool isVerified = true;
}
}
}
C# Variables:
In c#, Variables will represent storage locations, and each variable has a particular type that determines what type of
values can be stored in the variable.
❖ Syntax of C# Variables Declaration
Following is the syntax of declaring and initializing variables in the c# programming language.
• [Data Type] [Variable Name];
• [Data Type] [Variable Name] = [Value];
• [Access Specifier] [Data Type] [Variable Name] = [Value];
❖ C# Variables Declaration Example
using System;
namespace Tutlane
{
class Program
{
static void Main(string[] args)
{
int number = 10;
string name = "Suresh Dasari";
double percentage = 10.23;
char gender = 'M';
bool isVerified = true;
Console.WriteLine("Id: " + number);
Console.WriteLine("Name: " + name);
Console.WriteLine("Percentage: " + percentage); Console.WriteLine("Gender: " + gender);
Console.ReadLine();
}
}
}
C# Namespaces:
In c#, Namespace is used to organize multiple classes in our applications, reducing the code redundancy in our .NET
applications. By using the namespace keyword, we can define the namespaces in our c# applications.
namespace Tutlane
{
class Welcome
{
public void GreetMessage()
{
// your method code
}
}
}
If we observe the above syntax, we defined a namespace in c# using the namespace keyword.
C# Operators:
In c#, the Operator is a programming element that specifies what kind of operation needs to perform on operands or
variables. For example, an addition (+) operator in c# is used to perform the sum operation on operands.
✓ C# Arithmetic Operators
In c#, Arithmetic Operators are useful to perform basic arithmetic calculations like addition, subtraction, division,
etc. based on our requirements.
int result;
int x= 20,y= 10;
result = (x + y);
✓ C# Relational Operators
In c#, Relational Operators are useful to check the relation between two operands like we can determine whether
two operand values equal or not, etc. based on our requirements.
For example, we have integer variables a = 10, b = 20. If we apply a relational operator >= (a >= b), we will get the
result false because the variable “a” contains a value that is less than variable b.
✓ C# Logical Operators
In c#, Logical Operators are useful to perform the logical operation between two operands like AND, OR and NOT
based on our requirements and the operands must contain only Boolean values otherwise Logical Operators will
throw an error.
✓ C# Bitwise Operators
In c#, Bitwise Operators will work on bits and these are useful to perform the bit by bit operations such as Bitwise
AND (&), Bitwise OR (|), Bitwise Exclusive OR (^), etc. on operands and we can perform bit-level operations on
Boolean and integer data.
✓ C# Assignment Operators
In c#, Assignment Operators are useful to assign a new value to the operand and these operators will work with
only one operand.
C# Control Statement:
❖ C# IF Statement: The C# if statement tests the condition. It is executed if condition is true.
Syntax:
16
RESTRICTED
RESTRICTED
❖ C# IF-else Statement: The C# if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.
Syntax:
❖ C# switch Statement: The C# switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement in C#.
Syntax:
❖ C# For Loop: The C# for loop is used to iterate a part of the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or do-while loops.
The C# for loop is same as C/C++. We can initialize variable, check condition and increment/decrement value.
17
RESTRICTED
RESTRICTED
❖ C# While Loop: In C#, while loop is used to iterate a part of the program several times. If the number of iteration
is not fixed, it is recommended to use while loop than for loop.
❖ C# Do-While Loop: The C# do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while
loop.
❖ C# Break Statement: The C# break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.
C# Function:
18
RESTRICTED
RESTRICTED
Function is a block of code that has a signature. Function is used to execute statements specified in the code block. A
function consists of the following components:
✓ Function name: It is a unique name that is used to make Function call.
✓ Return type: It is used to specify the data type of function return value.
✓ Body: It is a block that contains executable statements.
✓ Access specifier: It is used to specify function accessibility in the application.
✓ Parameters: It is a list of arguments that we can pass to the function during call.
Example:
C# Arrays
Like other programming languages, array in C# is a group of similar types of elements that have contiguous memory
location. In C#, array is an object of base type System.Array. In C#, array index starts from 0. We can store only fixed set
of elements in C# array.
➢ C# Array Types
There are 3 types of arrays in C# programming:
• Single Dimensional Array: To create single dimensional array, you need to use square brackets
[] after the type.
Example: int[] arr = new int[5];//creating array
• Multidimensional Array: The multidimensional array is also known as rectangular arrays in C#. It
can be two dimensional or three dimensional. The data is stored in tabular form (row * column)
which is also known as matrix.
Example: int[,] arr=new int[3,3];//declaration of 2D array
int[,,] arr=new int[3,3,3];//declaration of 3D array
• Jagged Array: In C#, jagged array is also known as "array of arrays" because its elements are
arrays. The element size of jagged array can be different.
Example: int[][] arr = new int[2][];
19
RESTRICTED
RESTRICTED
C# this:
In c# programming, this is a keyword that refers to the current instance of the class.
✓ It can be used to refer current class instance variable. It is used if field names (instance variables) and parameter
names are same, that is why both can be distinguish easily.
✓ It can be used to pass current object as a parameter to another method.
✓ It can be used to declare indexers.
C# static class:
The C# static class is like the normal class but it cannot be instantiated. It can have only static members. The advantage
of static class is that it provides you guarantee that instance of static class cannot be created.
C# Enum:
Enum in C# is also known as enumeration. It is used to store a set of named constants such as season, days, month, size
etc. The enum constants are also known as enumerators. Enum in C# can be declared within or outside class and structs.
Enum constants has default values which starts from 0 and incremented to one by one. But we can change the default
value.
using System;
public class EnumExample
{
public enum Season { WINTER, SPRING, SUMMER, FALL }
C# Strings:
In C#, string is an object of System.String class that represent sequence of characters. We can perform many operations
on strings such as concatenation, comparision, getting substring, search, trim, replacement etc.
using System;
public class StringExample
{
public static void Main(string[] args)
{
string s1 = "hello";
20
RESTRICTED
RESTRICTED
Console.WriteLine(s1);
Console.WriteLine(s2);
}
}
C# StringBuilder:
In c#, StringBuilder is a class that is useful to represent a mutable string of characters, and it is an object of the
System.Text namespace. Like string in c#, we can use a StringBuilder to create variables to hold any text, a sequential
collection of characters based on our requirements.
In c#, both string and StringBuilder will represent a sequence of characters and perform the same kind of operations, but
the only difference is strings are immutable, and StringBuilder is mutable.
OOPs Concepts:
The key concepts of OOPs are
i. Abstraction
ii. Encapsulation
iii. Inheritance
iv. Polymorphism
Abstraction
Abstraction is "To represent the essential feature without representing the background details."
✓ Abstraction lets you focus on what the object does instead of how it does it.
✓ Abstraction provides a generalized view of your classes or objects by providing relevant information.
✓ Abstraction is the process of hiding the working style of an object and showing the information about an object
understandably.
21
RESTRICTED
RESTRICTED
Encapsulation:
Wrapping up a data member and a method together into a single unit (in other words, class) is called Encapsulation.
Encapsulation is like enclosing in a capsule. That is, enclosing the related operations and data related to an object into
that object.
Encapsulation is like your bag in which you can keep your pen, book, etcetera. It means this is the property of
encapsulating members and functions.
✓ Encapsulation means hiding the internal details of an object, in other words, how an object does something.
✓ Encapsulation prevents clients from seeing its inside view, where the behavior of the abstraction is
implemented.
✓ Encapsulation is a technique used to protect the information in an object from another object.
✓ Hide the data for security, such as making the variables private, and expose the property to access the private
data that will be public.
Suppose you are a Mobile Phone Manufacturer and have designed and developed a Mobile Phone design (a
class). Now by using machinery, you are manufacturing Mobile Phones (objects) for selling; when you sell your
Mobile Phone, the user only learns how to use the Mobile Phone but not how the Mobile Phone works.
This means that you are creating the class with functions and by with objects (capsules), of which you are
making available the functionality of your class by that object and without interference in the original class.
22
RESTRICTED
RESTRICTED
Inheritance
When a class includes a property of another class, it is known as inheritance. Inheritance is a process of object
reusability.
For example, a child includes the properties of its parents.
Hierarchical inheritance in C#: This is the type of inheritance in which there are multiple classes derived from one base
class. This type of inheritance is used when there is a requirement of one class feature that is needed in multiple classes.
Multilevel inheritance in C#: When one class is derived from another, this type of inheritance is called multilevel
inheritance.
23
RESTRICTED
RESTRICTED
C# does not support multiple inheritances of classes. To overcome this problem, we can use interfaces.
In the preceding program, the ICar class inherits the features of the two interfaces; hence this type of
inheritance is called Multiple Inheritance.
Polymorphism:
Polymorphism means one name, many forms. One function behaves in different forms. In other words, "Many forms of a
single object is called Polymorphism. It occurs when we have many classes that are related to each other by inheritance.
24
RESTRICTED
RESTRICTED
In the above example, we have created a class Program inside which we have two methods of the same name greet().
Here, one of the greet() methods takes no parameters and displays "Hello". While the other greet() method takes a
parameter and displays "Hello Tim". Hence, the greet() method behaves differently in different scenarios. Or, we can say
greet() is polymorphic.
C# Interface:
Interface in C# is a blueprint of a class. It is like an abstract class because all the methods declared inside the interface
are abstract methods. It cannot have a method body and cannot be instantiated. Declare an interface with a capital
letter I in front of the name.
In C#, an interface can be defined using the interface keyword. An interface can contain declarations of methods,
properties, indexers, and events. However, it cannot contain instance fields.
The following interface declares some basic functionalities for the file operations.
Example: C# Interface
interface IFile
{
void ReadFile();
25
RESTRICTED
RESTRICTED
To implement multiple interfaces in C#, you separate each included interface with a comma. For example, to include
both an Ishape and an IshapeDisplay interface in a Square class, you use the following:
Method Overloading:
Method Overloading is a type of polymorphism. It has several names like “Compile Time Polymorphism” or “Static
Polymorphism,” and sometimes it is called “Early Binding”.
Method Overloading means creating multiple methods in a class with the same names but different signatures
(Parameters). It permits a class, struct, or interface to declare multiple methods with the same name with unique
signatures. The compiler automatically calls the required method to check the number of parameters and their type
passed into that method.
Example:
Method Overriding:
26
RESTRICTED
RESTRICTED
Method Overriding is a type of polymorphism. It has several names like “Run Time Polymorphism” or “Dynamic
Polymorphism,” and sometimes it is called “Late Binding”.
Method Overriding means having two methods with the same name and same signatures [parameters]; one should be in
the base class, and another method should be in a derived class [child class]. You can override the functionality of a base
class method to create the same name method with the same signature in a derived class. You can achieve method
overriding using inheritance. Virtual and Override keywords are used to achieve method overriding.
Example:
27
RESTRICTED
RESTRICTED
11. How would you explain the four fundamental concepts of object-oriented programming?
Answer: The four fundamental concepts of object-oriented programming can be explained as follows:
✓ Encapsulation is the bundling of data, including the methods that operate on that data, into a single,
private unit
✓ Polymorphism is the ability of a type to take on many forms using a single interface
✓ Abstraction is the concealment of unnecessary program details so that the user only sees the essential
attributes
✓ Inheritance is the process where one class derives (or inherits) its attributes and methods from another
12. What are the four fundamental principles of Object-Oriented Programming (OOP) in C#?
Answer: The four fundamental principles of Object-Oriented Programming (OOP) in C# are:
• Encapsulation: Encapsulation is the process of bundling the data and the methods (functions) that
operate on the data within a single unit called a class. This helps to hide the implementation details from
the outside world, allowing access only through a well-defined interface.
• Inheritance: Inheritance is the ability of a class to inherit properties and methods from a parent class
(base class). This helps to promote code reusability and maintainability by allowing new classes (derived
classes) to reuse the functionality of existing classes without modifying them.
• Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common
superclass. This enables a single function or method to operate on multiple types of objects, making the
code more flexible and extensible.
• Abstraction: Abstraction is the process of simplifying complex systems by breaking them down into
smaller, more manageable parts. In OOP, abstraction is achieved through the use of abstract classes and
interfaces, which define the common properties and methods that a group of related classes should
have.
29
RESTRICTED
RESTRICTED
• public: Members declared as public are accessible from any part of the code. They have the least
restriction on their visibility. Example:
public class MyClass {
public int MyProperty;
}
• private: Members declared as private are only accessible within the same class. They have the most
restriction on their visibility and are used to encapsulate implementation details. Example:
class MyClass {
private int MyProperty;
}
• protected: Members declared as protected are accessible within the same class and any derived classes.
This access modifier is useful when you want to provide access to members for subclasses, but not for
the rest of the code. Example:
class MyClass {
protected int MyProperty;
}
• internal: Members declared as internal are accessible within the same assembly. This access modifier is
useful when you want to expose members within a single assembly but hide them from external
assemblies. Example:
class MyClass {
internal int MyProperty;
}
• protected internal: Members declared as protected internal are accessible within the same assembly
and any derived classes, even if they are defined in a different assembly. This access modifier combines
the functionality of both protected and internal. Example:
class MyClass {
protected internal int MyProperty;
}
30
RESTRICTED
RESTRICTED
often achieved through interfaces or abstract classes. Encapsulation enforces data hiding, while abstraction
hides unnecessary implementation details.
16. Explain the term "getter" and "setter" in the context of encapsulation and properties in C#.
Answer: A "getter" is a method that retrieves the value of a private field within a class. A "setter" is a method
that assigns a value to a private field. Getters and setters are used to encapsulate access to data and allow
controlled interaction with the internal state of an object.
31
RESTRICTED
RESTRICTED
Answer:
✓ Overriding means to change the functionality of a method without changing the signature.
✓ You can override a method in base class by creating a similar method in derived class.
✓ Base class method has to be marked with virtual keyword and you can override it in derived class using
override keyword.
✓ Derived class method will completely overrides base class method i.e. when you refer base class object
created by casting derived class object a method in derived class will be called.
25. What is Operator Overloading?
Answer:
✓ Overloaded operators are functions with special names the keyword operator followed by the symbol
for the operator being defined.
✓ Similar to any other function, an overloaded operator has a return type and a parameter list.
26. What is Interface?
Answer:
✓ An interface looks like a class, but it has no implementation.
✓ The only thing it contains is declarations of events, indexers, methods and/or properties.
✓ The reason interfaces only provide declarations is because they are inherited by structs and classes,
which must provide an implementation for each interface member declared.
27. What are the different techniques for overloading a method in C#?
Answer: Method overloading can be achieved in the three following ways:
✓ By using different types of data for parameters in a method
✓ By changing the number of parameters in a method
✓ By changing the order of parameters in a method
Interfaces allow you to define contracts that classes must adhere to, and a class can implement multiple
interfaces. This allows a class to inherit multiple sets of behavior without the limitations of multiple inheritance.
32
RESTRICTED
RESTRICTED
Here's an example demonstrating how to implement multiple inheritance-like behavior using interfaces in C#:
interface IShape
{
double CalculateArea();
}
interface IDrawable
{
void Draw();
}
In this example, the Circle class implements both the IShape and IDrawable interfaces. As a result, the
Circle class inherits the CalculateArea method from the IShape interface and the Draw method from the
IDrawable interface.
So, while C# doesn't support multiple inheritance in the same way as some other programming languages, it
does offer a more controlled and flexible approach to achieving similar results through interfaces.
31. What are the key differences among abstraction, polymorphism, inheritance, and encapsulation in C#?
33
RESTRICTED
RESTRICTED
Allows objects of Enhances code flexibility, Treating a base class Animal and
Polymorphism different types to be reusability, derived classes (Dog, Cat)
Enables a class to inherit Facilitates code reuse by Creating a hierarchy: Vehicle (base)
Inheritance properties and sharing common and Car (derived).
behaviors from another functionality and creating Car "is-a" Vehicle, inheriting Vehicle
class, creating a an "is-a" properties/methods.
34
RESTRICTED
RESTRICTED
relationship between
hierarchical structure. classes.
Bundles data and Ensures data integrity, Using private fields and public
Encapsulation methods into a single reduces unintended methods to control access
unit (class), controlling interactions, and separates to data and provide controlled
access to the implementation interactions.
35
RESTRICTED
RESTRICTED
1) Creational patterns:
Deal with object creation mechanisms, providing ways to create objects in a manner that is more flexible, controlled,
and efficient.
● Singleton Pattern
● Factory Method Pattern
● Abstract Factory Pattern
● Builder Pattern
● Prototype Pattern
2) Structural patterns:
focus on the composition, structure, and relationships between classes and objects, thereby promoting flexibility,
reusability, and maintainability in software design
● Adapter Pattern
● Bridge Pattern
● Composite Pattern
● Decorator Pattern
● Facade Pattern
● Flyweight Pattern
● Proxy Pattern
3) Behavioral patterns:
focus on the communication, interaction, and collaboration between objects in a way that promotes flexibility,
maintainability, and understandability of the software.
● Mediator Pattern
● Chain of Responsibility Pattern
● Command Pattern
● Interpreter Pattern
● Iterator Pattern
● Observer Pattern
● State Pattern
● Strategy Pattern
● Template Method Pattern
● Memento Pattern
❖ Façade Pattern: It is used as a camouflage to cover the complexities of a large system and therefore provides a
simple interface to the client. In other words, it is a wrapper class used to hide the implementation details.
36
RESTRICTED
RESTRICTED
❖ Mediator Pattern: The Mediator design pattern promotes loose coupling between classes by encapsulating the
interactions between these classes within a separate mediator object. The classes do not interact directly with
each other, instead, they use the mediator to communicate.
37
RESTRICTED
RESTRICTED
42. Can the Mediator Pattern be combined with other design patterns?
Answer: Yes, the Mediator Pattern can be combined with patterns like Singleton, Factory, and Observer to
create more comprehensive and flexible designs.
38
RESTRICTED
RESTRICTED
43. How does the Mediator Pattern differ from the Observer Pattern?
Answer: While both patterns facilitate communication between objects, the Mediator centralizes the
communication, whereas the Observer allows objects to subscribe and receive updates from a subject.
ASP.NET
Definition:
ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic
web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily.
ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a browser-to-server bilateral
communication and cooperation.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using the extensible and
reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net
framework.
The ASP.NET application codes can be written in any of the following languages:
➢ C#
➢ Visual Basic.Net
➢ Jscript
➢ J#
ASP.NET web forms extend the event-driven model of interaction to the web applications. The browser submits a web
form to the web server and the server returns a full markup page or HTML page in response.
All client-side user activities are forwarded to the server for stateful processing. The server processes the output of the
client actions and triggers the reactions.
Now, HTTP is a stateless protocol. ASP.NET framework helps in storing the information regarding the state of the
application, which consists of:
❖ Page state
The page state is the state of the client, i.e., the content of various input fields in the web form.
❖ Session state
The session state is the collective information obtained from various pages the user visited and worked with,
i.e., the overall session state.
The ASP.NET component model provides various building blocks of ASP.NET pages. Basically it is an object model, which
describes:
❖ Server-side counterparts of almost all HTML elements or tags, such as <form> and <input>.
❖ Server controls, which help in developing complex user-interface. For example, the Calendar control or the
Gridview control.
40
RESTRICTED
RESTRICTED
(8) ADO.NET
It is the technology used for working with data and databases. It provides access to data sources like SQL server, OLE
DB, XML etc. The ADO.NET allows connection to data sources for retrieving, manipulating, and updating data.
(13) LINQ
It imparts data querying capabilities to .Net languages using a syntax which is similar to the tradition query language
SQL.
I. User makes a request for accessing application resource, a page. Browser sends this request to the web server.
II. A unified pipeline receives the first request and the following events take place:
a. An object of the class ApplicationManager is created.
b. An object of the class HostingEnvironment is created to provide information regarding the resources.
c. Top level items in the application are compiled.
III. Response objects are created. The application objects such as HttpContext, HttpRequest and HttpResponse are
created and initialized.
IV. An instance of the HttpApplication object is created and assigned to the request.
V. The request is processed by the HttpApplication class. Different events are raised by this class for processing the
request.
41
RESTRICTED
RESTRICTED
➢ Page initialization - At this stage, the controls on the page are assigned unique ID by setting the UniqueID
property and the themes are applied. For a new request, postback data is loaded and the control properties are
restored to the view-state values.
➢ Page load - At this stage, control properties are set using the view state and control state values.
➢ Validation - Validate method of the validation control is called and on its successful execution, the IsValid
property of the page is set to true.
➢ Postback event handling - If the request is a postback (old request), the related event handler is invoked.
➢ Page rendering - At this stage, view state for the page and all controls are saved. The page calls the Render
method for each control and the output of rendering is written to the OutputStream class of the Response
property of page.
➢ Unload - The rendered page is sent to the client and page properties, such as Response and Request, are
unloaded and all cleanup done.
42
RESTRICTED
RESTRICTED
An event is an action or occurrence such as a mouse click, a key press, mouse movements, or any system-
generated notification. A process communicates through events. For example, interrupts are system-
generated events.
❖ Event Arguments
ASP.NET event handlers generally take two parameters and return void. The first parameter represents the
object raising the event and the second parameter is event argument.
SelectedIndexChanged OnSelectedIndexChanged Drop-down list, list box, radio button list, check box list.
❖ Default events
43
RESTRICTED
RESTRICTED
The default event for the Page object is Load event. Similarly, every control has a default event. For example, default
event for the button control is the Click event.
Control Default Event
AdRotator AdCreated
BulletedList Click
Button Click
Calender SelectionChanged
CheckBox CheckedChanged
CheckBoxList SelectedIndexChanged
DataGrid SelectedIndexChanged
DataList SelectedIndexChanged
DropDownList SelectedIndexChanged
HyperLink Click
ImageButton Click
ImageMap Click
LinkButton Click
ListBox SelectedIndexChanged
Menu MenuItemClick
RadioButton CheckedChanged
RadioButtonList SelectedIndexChanged
ASP.NET - Data Sources
A data source control interacts with the data-bound controls and hides the complex data binding processes.
These are the tools that provide data to the data bound controls and support execution of operations like
insertions, deletions, sorting, and updates.
Each data source control wraps a particular data provider-relational databases, XML documents, or custom
classes and helps in:
✓ Managing connection
✓ Selecting data
✓ Managing presentation aspects like paging, caching, etc.
44
RESTRICTED
RESTRICTED
✓ Manipulating data
There are many data source controls available in ASP.NET for accessing data from SQL Server, from ODBC or
OLE DB servers, from XML files, and from business objects.
Based on type of data, these controls could be divided into two categories:
✓ Hierarchical data source controls
✓ Table-based data source controls
The data source controls used for hierarchical data are:
❖ XMLDataSource - It allows binding to XML files and strings with or without schema information.
❖ SiteMapDataSource - It allows binding to a provider that supplies site map information.
SqlDataSource It represents a connection to an ADO.NET data provider that returns SQL data,
including data sources accessible via OLEDB and ODBC.
ObjectDataSource It allows binding to a custom .Net business object that returns data.
LinqdataSource It allows binding to the results of a Linq-to-SQL query (supported by ASP.NET 3.5
only).
45
RESTRICTED
RESTRICTED
46
RESTRICTED
RESTRICTED
• It is a built-in feature in ASP.NET that provides a way to manage user accounts and implement
authentication and authorization.
60. What is routing in ASP.NET MVC?
• Routing is the process of mapping URLs to controller actions in ASP.NET MVC applications.
61. What is the purpose of the Global.asax file?
• The Global.asax file contains application-level events and settings, such as handling application-
wide exceptions.
62. What is the difference between GET and POST requests in ASP.NET?
• GET requests are used to retrieve data from the server, while POST requests are used to send
data to the server for processing.
63. What is a Session in ASP.NET?
• Session is a server-side state management technique that allows data to be persisted across
multiple requests for a single user.
64. What is caching in ASP.NET?
• Caching is the process of storing frequently used data in memory to improve application
performance.
65. What is the Web.config file used for in ASP.NET?
• The Web.config file contains configuration settings for an ASP.NET application, including
database connections, authentication, and custom error pages.
66. What is a Master Page in ASP.NET?
• A Master Page is a template that defines the common structure and layout for a set of web
pages.
67. What is AJAX in ASP.NET?
• AJAX (Asynchronous JavaScript and XML) is a technique for making asynchronous requests to
the server to update parts of a web page without a full page refresh.
68. What is the role of the @ symbol in Razor views?
• The @ symbol is used to switch between HTML markup and C# code in Razor views.
69. What is the purpose of the ModelState object in ASP.NET MVC?
• ModelState is used to store validation errors and other data associated with form submission in
ASP.NET MVC applications.
70. What is Entity Framework in ASP.NET?
47
RESTRICTED
RESTRICTED
ASP.NET (MVC)
Overview: Definition
48
RESTRICTED
RESTRICTED
ASP.NET Core MVC is a rich framework for building web apps and APIs using the Model-View-Controller design pattern.
MVC stands for Model, View, and Controller. MVC separates an application into three components - Model, View, and
Controller. Each architecture component is built to handle specific development aspect of an application.
MVC separates the business logic and presentation layer from each other. It was traditionally used for desktop graphical
user interfaces (GUIs). Nowadays, MVC architecture in web technology has become popular for designing web
applications as well as mobile apps.
Model: Model represents the shape of the data. A class in C# is used to describe a model. Model objects store data
retrieved from the database. The Model in an MVC application represents the state of the application and any business
logic or operations that should be performed by it. Business logic should be encapsulated in the model, along with any
implementation logic for persisting the state of the application
View: Views are responsible for presenting content through the user interface. They use the Razor view engine to embed
.NET code in HTML markup. There should be minimal logic within views, and any logic in them should relate to presenting
content. If you find the need to perform a great deal of logic in view files in order to display data from a complex model,
consider using a View Component, ViewModel, or view template to simplify the view.
Controller: Controllers are the components that handle user interaction, work with the model, and ultimately select a
view to render. In an MVC application, the view only displays information; the controller handles and responds to user
input and interaction. In the MVC pattern, the controller is the initial entry point, and is responsible for selecting which
model types to work with and which view to render (hence its name - it controls how the app responds to a given request).
The following figure illustrates the flow of the user's request in ASP.NET MVC.
As per the above figure, when a user enters a URL in the browser, it goes to the webserver and routed to a controller. A
controller executes related view and models for that request and create the response and sends it back to the browser.
MVC Examples: Let’s see Model View Controller example from daily life:
49
RESTRICTED
RESTRICTED
50
RESTRICTED
RESTRICTED
▪ App_Data: The App_Data folder can contain application data files like LocalDB, .mdf files, XML files, and other
data related files. IIS will never serve files from App_Data folder.
▪ App_Start: The App_Start folder can contain class files that will be executed when the application starts.
Typically, these would be config files like AuthConfig.cs, BundleConfig.cs, FilterConfig.cs, RouteConfig.cs etc. MVC
5 includes BundleConfig.cs, FilterConfig.cs and RouteConfig.cs by default.
▪ Content: The Content folder contains static files like CSS files, images, and icons files. MVC 5 application includes
bootstrap.css, bootstrap.min.css, and Site.css by default.
▪ Controllers: The Controllers folder contains class files for the controllers. A Controller handles users' request and
returns a response. MVC requires the name of all controller files to end with "Controller".
▪ Fonts: The Fonts folder contains custom font files for your application.
▪ Models: The Models folder contains model class files. Typically, model class includes public properties, which will
be used by the application to hold and manipulate application data.
▪ Scripts: The Scripts folder contains JavaScript or VBScript files for the application. MVC 5 includes javascript files
for bootstrap, jquery 1.10, and modernizer by default.
▪ Views: The Views folder contains HTML files for the application. Typically view file is a .cshtml file where you
write HTML and C# or VB.NET code. The Views folder includes a separate folder for each controller. For example,
all the .cshtml files, which will be rendered by HomeController will be in View > Home folder.
▪ Global.asax: Global.asax file allows you to write code that runs in response to application-level events, such as
Application_BeginRequest, application_start, application_error, session_start, session_end, etc.
▪ Packages.config: Packages.config file is managed by NuGet to track what packages and versions you have
installed in the application.
51
RESTRICTED
RESTRICTED
Routing in MVC:
In the ASP.NET Web Forms application, every URL must match with a specific .aspx file. For example, a URL
http://domain/studentsinfo.aspx must match with the file studentsinfo.aspx that contains code and markup for rendering
a response to the browser.
Route: Route defines the URL pattern and handler information. All the configured routes of an application stored in
RouteTable and will be used by the Routing engine to determine appropriate handler class or file for an incoming request.
The following figure illustrates the Routing process.
Configure a Route:
As you can see in the above figure, the route is configured using the MapRoute() extension method of RouteCollection,
where name is "Default", url pattern is "{controller}/{action}/{id}" and defaults parameter for controller, action method
and id parameter. Defaults specify which controller, action method, or value of id parameter should be used if they do not
exist in the incoming request URL.
Action method: All the public methods of the Controller class are called Action methods. They are like any other
normal methods with the following restrictions:
• Action method must be public. It cannot be private or protected
• Action method cannot be overloaded
52
RESTRICTED
RESTRICTED
ActionResult: MVC framework includes various Result classes, which can be returned from an action method. The
result classes represent different types of responses, such as HTML, file, string, JSON, javascript, etc. The following table
lists all the result classes available in ASP.NET MVC.
In ASP.NET MVC, a user request is routed to the appropriate controller and action method. However, there may be
circumstances where you want to execute some logic before or after an action method executes. ASP.NET MVC provides
filters for this purpose.
MVC provides different types of filters. The following table list filter types, built-in filters, and interface that must be
implemented to create custom filters.
Filter Type Description Built-in Filter Interface
Authorization Performs authentication and authorizes before executing an [Authorize], IAuthorizationFilter
filters action method. [RequireHttps]
Action filters Performs some operation before and after an action method IActionFilter
executes.
Result filters Performs some operation before or after the execution of the [OutputCache] IResultFilter
view.
Exception filters Performs some operation if there is an unhandled exception [HandleError] IExceptionFilter
thrown during the execution of the ASP.NET MVC pipeline.
53
RESTRICTED
RESTRICTED
Scaffolding is a technique used by many MVC frameworks like ASP.NET MVC, Ruby on Rails, Cake PHP and Node. JS etc.,
to generate code for basic CRUD (create, read, update, and delete) operations against your database effectively. Further
you can edit or customize this auto generated code according to your need.
TempData: Software engineers can use the TempDataDictionary class to pass data through each request. It
holds on to the information and transfers data between controllers or actions. TempData stores temporary
information before removing it after the request is completed.
ViewData: This feature stores internal information. It uses typecasting to form complex data types and prevent
errors in the system. You can only use ViewData for a current request that contains key-value pairs in a
dictionary.
ViewBag: This dynamic property passes data from a controller to the desired view. This temporary data also
enables you to share values without the need for typecasting or a complex data type.
✓ Partial view: On the other hand, a partial view is an independent, modular view component that can be
included within another view. It can render HTML output within another file’s rendered output. Many
app developers use partial views to reuse parts of a UI across different views.
ASP.NET Web API is a framework for building services based on the Hypertext Transfer Protocol (HTTP). It
enables developers to build RESTful APIs that can be used for web applications.
54
RESTRICTED
RESTRICTED
Send applicants a REST API test to gain a basic understanding of their programming skills and ability to maintain
a scalable application programming interface.
The Default Route is defined by the MapRoute method in the RouteConfig.cs (or similar) file of your MVC
application. It typically follows the format:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
85. What is the difference between Temp data, View, and View Bag?
In Asp.Net MVC there are three ways to pass/store data between the controllers and views.
ViewData
✓ ViewData is used to pass data from controller to view
✓ It is derived from ViewDataDictionary class
55
RESTRICTED
RESTRICTED
Example:
@Html.TextBox("username", null, new { @class = "form-control" })
@Html.ActionLink("Home", "Index", "Home")
56
RESTRICTED
RESTRICTED
ASP.NET Core
Overview: Definition
ASP.NET Core is an open source and cloud-optimized web framework for developing modern web applications that can
be developed and run on Windows, Linux and the Mac. It includes the MVC framework, which now combines the features
of MVC and Web API into a single web programming framework.
The following is a default project structure when you create an empty ASP.NET Core application in Visual Studio.
57
RESTRICTED
RESTRICTED
➢ ASP.NET Core - wwwroot Folder: By default, the wwwroot folder in the ASP.NET Core project is treated as a
web root folder. Static files can be stored in any folder under the web root and accessed with a relative path to
that root.
➢ ASP.NET Core - Program.cs: ASP.NET Core web application is actually a console project which starts executing
from the entry point public static void Main() in Program class where we can create a host for the web application.
➢ ASP.NET Core - Startup Class: ASP.NET Core application must include Startup class. It is like Global.asax in the
traditional .NET application. As the name suggests, it is executed first when the application starts.
Middleware:
Middleware refers to components in ASP.NET Core that handle requests and responses in the request pipeline. Each
middleware can perform specific tasks, such as authentication, logging, and routing, as the request flows through the
pipeline.
58
RESTRICTED
RESTRICTED
Routing:
Routing in ASP.NET Core determines how URLs are mapped to controller actions. It directs incoming requests to the
appropriate controller based on defined routes.
Tag Helpers:
Tag Helpers are a feature in ASP.NET Core that enable you to create custom HTML-like elements that can include server-
side C# code. They enhance the readability and maintainability of views.
59
RESTRICTED
RESTRICTED
Logging:
Logging is the process of recording events and information during the execution of an application. ASP.NET Core provides
a built-in logging framework that allows developers to capture and manage logs for debugging and monitoring purposes.
ViewModel:
A ViewModel is a concept used to pass data from the Controller to the View. It's a separate class that contains only the
data needed for the View to render, helping to keep the View lightweight and focused on display logic.
ViewComponent:
A ViewComponent is a reusable UI component in ASP.NET Core that encapsulates a specific piece of functionality or
rendering logic. It's more lightweight than a full-blown controller and view and is often used for rendering widgets or parts
of a page.
60
RESTRICTED
RESTRICTED
Partial View:
A partial view is a reusable view component that can be included within other views. It's used to encapsulate and reuse
UI components across multiple views.
Web API:
A Web API (Application Programming Interface) is a set of HTTP endpoints that allow applications to communicate with
each other over the internet. ASP.NET Core allows developers to build RESTful Web APIs.
61
RESTRICTED
RESTRICTED
SignalR:
SignalR is a library in ASP.NET Core that enables real-time communication between clients and the server. It's particularly
useful for building applications that require live updates, such as chat applications or collaborative tools.
Docker:
Docker is a platform for developing, shipping, and running applications in containers. Containers provide a consistent and
isolated environment for applications to run, ensuring portability across different environments.
Session State:
Session state is a mechanism that allows the application to maintain user-specific data across multiple requests. ASP.NET
Core provides session management to store and retrieve user-specific information during a user's session.
ModelState:
ModelState is a property in the controller that holds information about the validation state of model data. It helps manage
and report validation errors and other model-related information.
62
RESTRICTED
RESTRICTED
Caching:
Caching involves storing frequently accessed data in memory to reduce the load on the server and improve performance.
ASP.NET Core provides caching mechanisms that can be applied to various types of data.
63
RESTRICTED
RESTRICTED
• build web applications, IoT (Internet of things) apps, services and mobile Backends.
• run on .Net Core.
• You can do your development on Linux, Windows and MacOS.
• deploy your code to cloud or on-premises.
90. 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.
64
RESTRICTED
RESTRICTED
Asp.Net Supports WebForm, Asp.Net MVC and Asp.Net Asp.Net Core does not support WebForm. It supports
WebAPI. MVC, Web API and Asp.Net Web pages originally added
in .Net Core 2.0.
Asp.Net used the only IIS with dependent on Asp.Net Core has not dependent System.web.dll and so
System.web.dll. the IIS.
Support C#, VB and many other languages and also Support only C#, F# language. VB support to added a
support WCF, WPF and WF short time and no support WCF, WPF and WF but support
for WCF client libraries are available.
Asp.Net MVC application added Web.config, Global.asax, Core did not support Web.config and Global.asax files. It
Application Start. is supporting appsettings.json.
Container support not more than better as the ASP.Net Container support best suited for deployments like
Core application. Docker.
All major versions supported Support Core from Visual Studio 2015 update 3 and
current version VS 2017.
We Need to re-compile after the code change. Core Browser refresh will compile and executed the code
no need for re-compile.
HTTP is a protocol that allows the fetching of resources, such as HTML documents. It is the foundation of any
data exchange on the Web, and it is a client-server protocol, which means requests are initiated by the recipient,
usually the Web browser.
65
RESTRICTED
RESTRICTED
The Startup class in ASP.NET Core plays a pivotal role in configuring and setting up your application's behavior,
services, middleware, and more. 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.
The Startup class is typically found in the Startup.cs file and contains two primary methods: ConfigureServices
and Configure.
app.UseHttpsRedirection();
// other middleware components
}
}
66
RESTRICTED
RESTRICTED
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.
102. 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:
67
RESTRICTED
RESTRICTED
.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();
}
✓ 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.
68
RESTRICTED
RESTRICTED
{
await context.Response.WriteAsync("Hello World!");
});
});
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
69
RESTRICTED
RESTRICTED
Filters provide the capability to run the code before or after the specific stage in request processing pipeline, it
could be either MVC app or Web API service. Filters performs the tasks like Authorization, Caching
implementation, Exception handling etc. ASP.NET Core also provide the option to create custom filters. There
are 5 types of filters supported in ASP.NET Core Web apps or services.
✓ Authorization filters run before all or first and determine the user is authorized or not.
✓ Resource filters are executed after authorization. OnResourceExecuting filter runs the code before
rest of filter pipeline and OnResourceExecuted runs the code after rest of filter pipeline.
✓ Action filters run the code immediately before and after the action method execution. Action filters
can change the arguments passed to method and can change returned result.
✓ Exception filters used to handle the exceptions globally before wrting the response body
✓ Result filters allow to run the code just before or after successful execution of action results
111. 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 the URL) that are used to process the request. Using the route, routing can find a route handler
based on the URL. All the routes are registered when the application is started. There are two types of routing
supported by ASP.NET Core
✓ The conventional routing
✓ Attribute routing
112. What are the various JSON files available in ASP.NET Core?
There are the following JSON files in ASP.NET Core :
✓ global.json
✓ launchsettings.json
✓ appsettings.json
✓ bundleconfig.json
✓ bower.json
✓ package.json
113. 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 features 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 files, but it is not really a code-behind file. It is a class
inherited from PageModel class.
114. 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.
70
RESTRICTED
RESTRICTED
✓ 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.
71
RESTRICTED
RESTRICTED
Answer: Middleware in ASP.NET Core are components that handle requests and responses. They are executed in
the pipeline sequentially. Middleware can perform tasks like logging, authentication, authorization, and more.
Developers can add, remove, or reorder middleware to customize the request handling process.
121. What is the difference between Razor Pages and MVC in ASP.NET Core?
Answer: Razor Pages and MVC are both patterns for building web applications. MVC (Model-View-Controller)
separates concerns into distinct components. Razor Pages, on the other hand, emphasizes simpler page-focused
development, where each page can have its own model and handler. MVC is better suited for complex
applications, while Razor Pages are great for simpler scenarios.
123. How do you configure and use authentication and authorization in ASP.NET Core?
Answer: Authentication is configured using services.AddAuthentication() in Startup.cs, with strategies like JWT,
OAuth, etc. Authorization is configured with services.AddAuthorization(), specifying policies and requirements,
which are then applied to controllers or actions using attributes.
124. What is Entity Framework Core and how does it relate to ASP.NET Core?
Answer: Entity Framework Core (EF Core) is an Object-Relational Mapping (ORM) framework for database
access. It allows you to work with databases using .NET objects. EF Core is commonly used with ASP.NET Core to
simplify database operations and data modeling.
72
RESTRICTED
RESTRICTED
126. How does ASP.NET Core handle asynchronous programming, and why is it important?
Answer: ASP.NET Core leverages asynchronous programming to improve scalability and responsiveness. It uses
asynchronous I/O operations to avoid blocking threads, allowing the server to handle more requests
concurrently.
127. Explain the concept of custom middleware in ASP.NET Core. Provide an example.
Answer: Custom middleware are components that you can write and inject into the ASP.NET Core pipeline. They
process requests and responses. An example middleware might log information before and after the request is
handled.
public class MyCustomMiddleware
{
private readonly RequestDelegate _next;
await _next(context);
128. Describe the hosting models for ASP.NET Core applications and when you would use each one (Kestrel, IIS,
etc.).
Answer: ASP.NET Core supports various hosting models like Kestrel, IIS, and others. Kestrel is a cross-platform,
lightweight web server suitable for directly serving ASP.NET Core applications. IIS can act as a reverse proxy to
Kestrel on Windows. Choose the appropriate hosting model based on deployment scenarios and requirements.
129. How can you optimize the performance of an ASP.NET Core application?
73
RESTRICTED
RESTRICTED
Answer: Caching in ASP.NET Core can be achieved through various mechanisms, including:
133. Explain the concept of CORS (Cross-Origin Resource Sharing) in ASP.NET Core and how it can be configured?
Answer: CORS is a security feature that controls how web pages or APIs hosted on one domain can request
resources from another domain. In ASP.NET Core, CORS can be configured using the AddCors method in
Startup.cs, specifying allowed origins, HTTP methods, headers, and more. This ensures that only trusted origins
can access resources on the server.
134. What is the default web server used by ASP.NET Core applications?
Answer: The default web server used by ASP.NET Core applications is Kestrel.
135. What are the key features of the Kestrel web server?
Answer: Kestrel is a cross-platform, lightweight, and high-performance web server. It supports HTTP/1.x and
HTTP/2, has asynchronous I/O capabilities for handling a large number of concurrent connections efficiently, and
can be used as an edge server or behind a reverse proxy.
136. Can you name some other web servers that can be used with ASP.NET Core, besides Kestrel?
Answer: Besides Kestrel, other web servers that can be used with ASP.NET Core include Internet Information
Services (IIS), Apache, and Nginx.
137. What are the steps involved in deploying an ASP.NET Core application using Kestrel?
Answer: Deploying an ASP.NET Core application using Kestrel typically involves:
74
RESTRICTED
RESTRICTED
138. How can you configure Kestrel options in an ASP.NET Core application?
Answer: Kestrel options can be configured using the WebHostBuilder in the Program.cs file. You can set options
such as listening endpoints, SSL certificates, maximum connections, and more. For more advanced
configuration, you can access the KestrelServerOptions directly.
139. What is Redis caching, and why is it beneficial for ASP.NET Core applications?
Answer: Redis caching is a high-performance, distributed, in-memory data store. It serves as a key-value cache
that stores frequently used data in memory, providing fast access and reducing the load on the database. In
ASP.NET Core, Redis caching improves application performance by reducing data retrieval times and enhancing
scalability.
141. How can you configure and use Redis caching in an ASP.NET Core application?
Answer: To use Redis caching in ASP.NET Core, you need to:
✓ Install the StackExchange.Redis NuGet package.
✓ Configure the Redis connection in the appsettings.json file.
✓ Add Redis caching services in Startup.cs using services.AddDistributedRedisCache().
142. What is MongoDB, and why might it be a suitable choice for data storage in ASP.NET Core applications?
Answer: MongoDB is a NoSQL database that stores data in a flexible, schema-less document format. It's suitable
for ASP.NET Core applications that require high flexibility and scalability, as it allows developers to store and
retrieve complex, unstructured data without adhering to a rigid schema.
143. What is the purpose of the wwwroot folder in an ASP.NET Core project?
Answer: The wwwroot folder is where static files like CSS, JavaScript, and images are stored. These files are
served directly to clients without any processing.
144. How can you publish an ASP.NET Core application for deployment?
Answer: You can publish an ASP.NET Core application using the dotnet publish command, which compiles the
application and its dependencies into a deployable package.
146. How can you pass data from a controller action to a view in ASP.NET Core?
75
RESTRICTED
RESTRICTED
Answer: Data can be passed from a controller to a view using a model. In the controller action, you create an
instance of the model, populate it with data, and pass it to the view using the return View(model) statement.
147. How can you handle HTTP GET and POST requests in ASP.NET Core?
Answer: HTTP GET requests are typically handled by controller action methods decorated with [HttpGet]
attributes. HTTP POST requests are handled similarly using [HttpPost] attributes.
148. What is the role of the Startup class in an ASP.NET Core application?
Answer: The Startup class is used to configure services and the application's request pipeline, including
middleware, routing, and dependency injection.
151. How can you manage environment-specific configuration in an ASP.NET Core application?
Answer: Environment-specific configuration can be managed using the appsettings.json file along with
appsettings.{Environment}.json files, where {Environment} is the current environment name (e.g.,
appsettings.Production.json).
152. What is the purpose of the [HttpGet] and [HttpPost] attributes in controller actions?
Answer: [HttpGet] and [HttpPost] attributes specify the HTTP verb that the action should respond to. They allow
you to define separate methods for handling GET and POST requests.
154. What is the purpose of the IActionResult interface in ASP.NET Core actions?
Answer: IActionResult is used to represent the result of an action method. It allows you to return different types
of results, such as views, JSON data, redirects, and more.
155. What is the purpose of the [FromBody] attribute in a controller action parameter?
Answer: The [FromBody] attribute indicates that the parameter value should be bound from the request body in
API controller actions.
76
RESTRICTED
RESTRICTED
160. How can you return a JSON response from an ASP.NET Core controller action?
Answer: You can return a JSON response using the Json() method in a controller action, passing the data you
want to serialize as a parameter.
162. What is the difference between asynchronous and synchronous programming in ASP.NET Core?
Answer: Synchronous programming blocks the execution of code until a task is complete, while asynchronous
programming allows the code to continue executing while waiting for a task to finish.
165. What is the difference between async and await in asynchronous programming?
Answer: async is used to declare a method as asynchronous, while await is used to indicate a point where the
method can asynchronously wait for a task to complete.
168. What is multithreading, and how does it relate to concurrency in ASP.NET Core?
Answer: Multithreading is the concurrent execution of multiple threads within a single process. In ASP.NET Core,
multithreading allows the application to handle multiple requests simultaneously, improving concurrency.
77
RESTRICTED
RESTRICTED
170. How can you create and use a View Component in ASP.NET Core?
Answer: To create a View Component, you create a class derived from ViewComponent. You can invoke it within
a view using the @await Component.InvokeAsync("ComponentName") syntax.
Authentication: Authentication is the process of verifying the identity of a user, typically through credentials like a
username and password. .NET Core provides a robust authentication framework that supports various authentication
methods and external identity providers.
✓ Authentication Middleware: .NET Core includes authentication middleware that can handle various
authentication schemes, such as cookies, tokens, and more. Middleware intercepts incoming requests and
handles authentication logic.
✓ Identity Providers: You can integrate with external identity providers like OAuth, OpenID Connect, or external
identity systems like Azure Active Directory. This enables users to log in using their existing accounts from other
services.
✓ Claim-Based Identity: .NET Core uses claims to represent user identities. Claims are statements about the user,
such as their roles, name, or email. Claims-based authentication is flexible and allows you to make access control
decisions based on these claims.
Authorization: Authorization is the process of determining whether an authenticated user has the necessary permissions
to access a particular resource or perform a specific action within an application.
✓ Policy-Based Authorization: .NET Core provides policy-based authorization, where you define authorization
policies that dictate who can access specific resources based on user roles or claims.
✓ Authorization Middleware: Similar to authentication middleware, .NET Core has authorization middleware that
examines incoming requests and checks whether the user has the required permissions based on the defined
policies.
✓ Roles and Claims: You can use roles and claims to manage authorization. Roles represent groups of users with
specific permissions, while claims can be used to make fine-grained authorization decisions based on attributes.
✓ Attribute-Based Authorization: You can apply authorization attributes to controllers and actions to specify who
can access them. For example, the [Authorize] attribute restricts access to authenticated users.
Combining Authentication and Authorization: Authentication and authorization often go hand in hand. Once a user is
authenticated, authorization determines what they're allowed to do within the application.
✓ Policy-Based Authentication: You can use authentication policies to enforce specific authentication requirements
before authorization policies are evaluated. For example, ensuring a user is authenticated with a specific identity
provider.
78
RESTRICTED
RESTRICTED
✓ Custom Requirements: You can create custom authorization requirements and handlers to implement complex
authorization scenarios that go beyond simple roles or claims.
171. What's the key difference between authentication and authorization in .NET Core?
Answer: Authentication verifies the identity of a user, while authorization controls what actions or resources a
user is allowed to access.
172. What's the purpose of the AllowAnonymous attribute in .NET Core authentication?
Answer: The AllowAnonymous attribute overrides any global or controller-level authorization policies, allowing
anonymous access to specific actions or controllers.
173. How can you implement OAuth-based authentication in a .NET Core application?
Answer: You can use middleware like AddOAuth or AddOpenIdConnect to integrate OAuth-based authentication.
Configure the client and identity provider details to enable OAuth authentication.
178. Can you explain the concept of "bearer token" in token-based authentication?
Answer: A bearer token is a token included in the request header that grants access to a protected resource. It's
used in token-based authentication to authenticate and authorize API requests.
79
RESTRICTED
RESTRICTED
179. How can you customize the behavior of the [Authorize] attribute for specific actions?
Answer: You can use the [Authorize] attribute with policy names, like [Authorize(Policy = "CustomPolicy")], to
enforce custom authorization rules on specific actions.
180. Explain how you can handle authentication and authorization for API endpoints in a .NET Core application.
Answer: Use authentication middleware to validate user identity, and then apply authorization policies to
controllers or actions using attributes like [Authorize]. This ensures that only authenticated and authorized users
can access the API endpoints.
181. How can you implement two-factor authentication in a .NET Core application?
Answer: You can use the built-in SignInManager to implement two-factor authentication by adding an additional
layer of verification, such as a code sent to the user's email or phone.
Configuration Providers: Configuration data in .NET Core is provided by configuration providers. These providers
retrieve configuration values from different sources such as environment variables, JSON files, XML files, command-line
arguments, and more. Providers are used to load configuration data into your application.
Configuration Hierarchy: The configuration framework in .NET Core supports a hierarchical structure. Configuration
values are resolved in a specific order, allowing you to override settings at different levels. The hierarchy typically
includes:
✓ appsettings.json: A JSON file where you can store configuration settings. It supports hierarchical structures for
easy organization.
✓ appsettings.{Environment}.json: JSON files for specific environments, allowing you to override settings based on
the environment.
✓ Environment Variables: Configuration values can be sourced from environment variables.
✓ Command-Line Arguments: You can pass configuration values through command-line arguments when running
your application.
Configuration API: .NET Core provides an API to access configuration values in your application. The IConfiguration
interface and its associated classes allow you to read configuration values and bind them to strongly typed objects.
Options Pattern: The Options pattern in .NET Core allows you to define strongly typed classes to represent different
sections of your configuration data. This makes it easier to work with configuration values and provides better type
safety.
80
RESTRICTED
RESTRICTED
Dependency Injection: The configuration framework integrates seamlessly with the .NET Core dependency injection
system. You can inject configuration values into your services and components using constructor injection.
Reloadable Configuration: .NET Core configuration supports automatic reloading of configuration values when they
change. This is particularly useful for scenarios where you want your application to respond dynamically to configuration
updates without restarting.
Secure Configuration: Sensitive configuration data, such as connection strings or API keys, can be stored securely using
user secrets or environment-specific configuration files.
81
RESTRICTED
RESTRICTED
188. Can you explain the differences between transient, scoped, and singleton lifetimes in dependency injection?
Answer: Transient lifetime creates a new instance of a dependency every time it's requested, scoped lifetime
creates a single instance per scope (e.g., per HTTP request), and singleton lifetime creates a single instance for
the entire application's lifespan. Choosing the appropriate lifetime is crucial to managing resource usage and
object state.
189. What is the purpose of named or keyed registrations in dependency injection?
Answer: Named or keyed registrations allow you to register multiple implementations of the same interface or
base class under different names or keys. This is useful when you need to differentiate between different
implementations and select the appropriate one dynamically based on runtime conditions.
190. What is the role of the ServiceProviderFactory in .NET Core dependency injection?
Answer: The ServiceProviderFactory is responsible for creating and configuring the IServiceProvider instance
that manages the application's dependencies. It allows you to customize the DI container's behavior, such as
adding additional services or modifying the default registrations.
191. How can you control disposal of IDisposable objects created through dependency injection?
Answer: You can control the disposal of IDisposable objects by specifying their lifetimes appropriately. For
example, with a scoped or request-specific lifetime, IDisposable objects will be automatically disposed of at the
end of the scope or request.
192. What is the difference between compile-time and runtime DI containers?
Answer: Compile-time DI containers perform dependency resolution and object creation at compile time, often
using code generation. Runtime DI containers resolve dependencies at runtime, typically using reflection.
Compile-time containers offer performance advantages and early error detection, while runtime containers
offer more flexibility.
193. What are some potential drawbacks or challenges of using dependency injection?
Answer: Some challenges include increased complexity in large projects, potential performance overhead due to
reflection or container setup, and difficulties in handling complex object graphs or circular dependencies. Proper
design and understanding of DI principles can help mitigate these challenges.
194. How can you configure Redis caching in a .NET Core application?
Answer: You can configure Redis caching by adding the Microsoft.Extensions.Caching.StackExchangeRedis
package, registering the RedisCache service in Startup.cs, and specifying the Redis server connection details in
your configuration.
195. What is the purpose of using Redis as a distributed cache in .NET Core?
Answer: Redis serves as a fast and scalable in-memory data store. It can be used as a distributed cache to
improve application performance by reducing the load on the primary data store and providing low-latency
access to frequently accessed data.
196. How can you handle cache expiration and eviction policies in Redis caching?
Answer: In Redis caching, you can set cache expiration using the Set method with a TimeSpan. Redis also
supports eviction policies, such as LRU (Least Recently Used) and LFU (Least Frequently Used), which can be
configured to automatically remove items when the cache reaches a certain size.
82
RESTRICTED
RESTRICTED
197. What are the potential challenges or considerations when using Redis caching?
Answer: Some challenges include ensuring data consistency between the cache and the primary data store,
handling cache misses efficiently, and monitoring the cache's memory usage and performance.
198. How can you configure MongoDB in a .NET Core application?
Answer: To configure MongoDB, you need to install the MongoDB.Driver package, set up the connection string
in your appsettings.json, and register the IMongoClient service in Startup.cs.
199. What is the primary benefit of using MongoDB in a .NET Core application?
Answer: MongoDB is a NoSQL database that provides flexibility in storing and querying data. It's suitable for
scenarios where the data structure is dynamic and may evolve over time.
200. How can you perform CRUD operations using the MongoDB driver in .NET Core?
Answer: The MongoDB driver provides methods for CRUD operations. For example, you can use the
InsertOneAsync, Find, UpdateOneAsync, and DeleteOneAsync methods to create, read, update, and delete
documents.
201. How can you model relationships between documents in MongoDB?
Answer: MongoDB supports embedded documents and references for modeling relationships. You can embed
one document within another or use references (such as ObjectId references) to link documents in separate
collections.
Logging in ASP.NET Core: ASP.NET Core provides a flexible and extensible logging framework that allows you to capture
various types of log information and route it to different targets. Here's how you can set up logging in your ASP.NET Core
application:
✓ Logging Providers: ASP.NET Core supports various logging providers such as Console, Debug, EventLog,
TraceSource, and more. You can choose one or more providers to which you want to route your log messages.
✓ Logging Levels: Log messages are categorized into different levels such as Information, Warning, Error, and
Critical. You can control which log levels are captured and displayed based on your application's needs.
✓ Logging Configuration: Logging configuration can be done in the appsettings.json or
appsettings.Development.json files. You can specify the logging levels, providers, and their settings in these
configuration files.
83
RESTRICTED
RESTRICTED
✓ Logging Middleware: ASP.NET Core also offers a logging middleware that can log requests and responses,
making it useful for diagnosing issues related to incoming HTTP requests.
Monitoring in ASP.NET Core: Monitoring involves tracking the health, performance, and usage of your application in
real-time. Here are some steps to set up monitoring in your ASP.NET Core application:
✓ Application Insights: Application Insights is a powerful monitoring and telemetry service provided by Microsoft.
It allows you to collect data about your application's usage, performance, and more. You can integrate
Application Insights into your ASP.NET Core application using its SDK.
✓ Health Checks: ASP.NET Core includes a health checking framework that enables you to define custom health
checks for various components of your application. These health checks can be used to determine the overall
health of your application and its dependencies.
✓ Metrics Collection: You can use third-party libraries or frameworks like Prometheus.NET to collect and expose
metrics from your application. These metrics can help you monitor performance and resource utilization.
✓ Distributed Tracing: Distributed tracing tools like OpenTelemetry can help you track the flow of requests across
various services in a microservices architecture, allowing you to identify bottlenecks and latency issues.
✓ Error Tracking: Integrating error tracking tools like Sentry or Raygun can help you capture and analyze
application errors in real-time.
Answer: You can implement request-response logging using a custom Middleware in ASP.NET Core.
205. Explain the concept of distributed tracing. How can you implement it in an ASP.NET Core microservices
architecture?
Answer: Distributed tracing is the practice of tracking requests as they flow through a distributed system,
allowing you to monitor the interactions between different services. In ASP.NET Core microservices architecture,
you can implement distributed tracing using tools like OpenTelemetry.
OpenTelemetry provides instrumentation libraries that you can add to your services to capture trace data. These
libraries generate unique trace IDs for each request and annotate them with context information. Trace data is
then collected by tracing backends like Jaeger or Zipkin for visualization and analysis.
206. How can you implement health checks in ASP.NET Core, and why are they important for monitoring?
Answer: Health checks are used to determine the operational status of different components of your
application. They are important for monitoring because they provide insights into the overall health of your
application and its dependencies. In ASP.NET Core, you can implement health checks by:
✓ Creating health check classes that implement the IHealthCheck interface.
✓ Registering these health checks in the ConfigureServices method using services.AddHealthChecks().
✓ Adding the health check endpoints to your application using app.UseHealthChecks() in the Configure
method.
Health checks can be used to monitor the availability of databases, third-party APIs, and other components,
ensuring that your application operates smoothly.
207. Explain the concept of log enrichment in ASP.NET Core. How can you achieve it?
Answer: Log enrichment involves adding additional contextual information to log entries to provide more insights
into the application's behavior. This is often used to enhance troubleshooting and analysis. In ASP.NET Core, you
can achieve log enrichment by implementing custom log enrichers. These enrichers can access the LogEvent and
add properties or data to it before it's written to the log. This is particularly useful for adding user-related
information, request-specific data, or environment details.
208. What is the purpose of log correlation IDs, and how can you implement them in ASP.NET Core?
Answer: Log correlation IDs are unique identifiers that are attached to logs related to a specific request or
transaction. They allow you to trace a series of log entries back to a single action or event, even in distributed
systems. In ASP.NET Core, you can implement log correlation IDs by generating a unique identifier for each request
and adding it to the log context. This identifier can be stored in the HttpContext or generated as part of a
middleware, and then included in every log entry related to that request.
209. How can you handle and log unhandled exceptions globally in an ASP.NET Core application?
Answer: To handle and log unhandled exceptions globally in an ASP.NET Core application, you can use the
IExceptionHandler middleware. This middleware catches exceptions that occur during the request processing
pipeline and logs them.
210. What are some challenges you might face when monitoring a containerized ASP.NET Core application in a
Kubernetes cluster?
Answer: Monitoring containerized ASP.NET Core applications in a Kubernetes cluster presents some unique
challenges due to the dynamic and distributed nature of container orchestration. Challenges include:
85
RESTRICTED
RESTRICTED
✓ Service Discovery: Ensuring that logs and metrics from all instances of the application are correctly
aggregated and monitored.
✓ Ephemeral Nature: Containers can be created and destroyed dynamically, requiring a solution to capture
logs and metrics before containers are terminated.
✓ Resource Isolation: Ensuring that monitoring tools don't consume excessive resources within the
containers.
✓ Networking Complexity: Handling networking challenges when dealing with services and pods in
Kubernetes, especially in distributed tracing scenarios.
Solutions often involve integrating with Kubernetes-native monitoring and logging tools, such as Prometheus for
metrics and Grafana for visualization.
211. Question: Describe the concept of log sampling. When might you use it, and how can you implement it in ASP.NET
Core?
Answer: Log sampling involves selectively capturing and recording only a portion of log entries, rather than
capturing every single log event. This can help reduce the volume of logs generated in high-traffic applications
while still providing a representative sample for analysis. Log sampling might be used when you want to balance
the need for insights with the performance impact of extensive logging. In ASP.NET Core, you can implement log
sampling by adding custom logic to decide whether a log entry should be recorded based on predefined criteria,
such as a random chance or certain conditions being met.
86
RESTRICTED
RESTRICTED
build a series of processing steps to handle various tasks, such as authentication, routing, logging, and more. Each
middleware component can modify the request or response or even short-circuit the pipeline.
In other words, it’s the layer that every request and response have to go through.
I. Middleware Components: Middleware components are classes that handle specific tasks in the request pipeline.
They can be built-in ASP.NET Core middleware or custom middleware that you define. Examples of built-in
middleware include authentication, static files handling, and routing.
II. Order of Execution: Middleware components are executed in the order they are added to the pipeline. The order
is significant because the output of one middleware becomes the input for the next. The first middleware is closest
to the client, while the last middleware is closest to the application.
III. Middleware Configuration: Middleware components are added to the pipeline during application startup in the
Configure method of the Startup class. The Use extension methods are used to add and configure middleware.
IV. Request and Response Processing: Middleware can modify the incoming request and its context or modify the
outgoing response. This allows you to manipulate headers, content, or any other aspect of the request and
response.
V. Short-Circuiting the Pipeline: Middleware components can decide to stop processing and return a response
without invoking subsequent middleware. This can be useful for implementing authentication checks or handling
specific scenarios.
VI. Chaining Middleware: Middleware can be chained together to build complex processing flows. The output of one
middleware becomes the input for the next, allowing you to compartmentalize and modularize your application's
logic.
VII. Custom Middleware: You can create custom middleware by implementing the IMiddleware interface or using the
UseMiddleware<T> extension method. This enables you to add application-specific logic to the pipeline.
Middleware order: The following diagram shows the complete request processing pipeline for ASP.NET Core MVC and
Razor Pages apps. You can see how, in a typical app, existing middlewares are ordered and where custom middlewares
are added. You have full control over how to reorder existing middlewares or inject new custom middlewares as necessary
for your scenarios.
87
RESTRICTED
RESTRICTED
Built-in middleware
ASP.NET Core ships with the following middleware components. The Order column provides notes on middleware
placement in the request processing pipeline and under what conditions the middleware may terminate request
processing.
Authentication Provides authentication support. Before HttpContext.User is needed. Terminal for OAuth
callbacks.
Cookie Policy Tracks consent from users for Before middleware that issues cookies. Examples:
storing personal information and Authentication, Session, MVC (TempData).
enforces minimum standards for
cookie fields, such
as secure and SameSite.
CORS Configures Cross-Origin Resource Before components that use CORS. UseCors currently must
Sharing. go before UseResponseCaching due to this bug.
DeveloperExceptionPage Generates a page with error Before components that generate errors. The project
information that is intended for templates automatically register this middleware as the
use only in the Development first middleware in the pipeline when the environment is
environment. Development.
Diagnostics Several separate middlewares Before components that generate errors. Terminal for
that provide a developer exceptions or serving the default web page for new apps.
exception page, exception
handling, status code pages, and
the default web page for new
apps.
Forwarded Headers Forwards proxied headers onto Before components that consume the updated fields.
the current request. Examples: scheme, host, client IP, method.
Health Check Checks the health of an ASP.NET Terminal if a request matches a health check endpoint.
Core app and its dependencies,
such as checking database
availability.
88
RESTRICTED
RESTRICTED
HTTP Logging Logs HTTP Requests and At the beginning of the middleware pipeline.
Responses.
HTTP Method Override Allows an incoming POST request Before components that consume the updated method.
to override the method.
HTTPS Redirection Redirect all HTTP requests to Before components that consume the URL.
HTTPS.
HTTP Strict Transport Security enhancement Before responses are sent and after components that
Security (HSTS) middleware that adds a special modify requests. Examples: Forwarded Headers, URL
response header. Rewriting.
OWIN Interop with OWIN-based apps, Terminal if the OWIN Middleware fully processes the
servers, and middleware. request.
Output Caching Provides support for caching Before components that require caching. UseRouting must
responses based on configuration. come before UseOutputCaching. UseCORS must come
before UseOutputCaching.
Response Caching Provides support for caching Before components that require caching. UseCORS must
responses. This requires client come before UseResponseCaching. Is typically not
participation to work. Use output beneficial for UI apps such as Razor Pages because
caching for complete server browsers generally set request headers that prevent
control. caching. Output caching benefits UI apps.
Request Decompression Provides support for Before components that read the request body.
decompressing requests.
Response Compression Provides support for compressing Before components that require compression.
responses.
Request Localization Provides localization support. Before localization sensitive components. Must appear
after Routing Middleware when
using RouteDataRequestCultureProvider.
Endpoint Routing Defines and constrains request Terminal for matching routes.
routes.
SPA Handles all requests from this Late in the chain, so that other middleware for serving
point in the middleware chain by static files, MVC actions, etc., takes precedence.
returning the default page for the
Single Page Application (SPA)
89
RESTRICTED
RESTRICTED
Session Provides support for managing Before components that require Session.
user sessions.
Static Files Provides support for serving static Terminal if a request matches a file.
files and directory browsing.
URL Rewrite Provides support for rewriting Before components that consume the URL.
URLs and redirecting requests.
W3CLogging Generates server access logs in At the beginning of the middleware pipeline.
the W3C Extended Log File
Format.
WebSockets Enables the WebSockets protocol. Before components that are required to accept WebSocket
requests.
213. Can you give an example scenario where you would use custom middleware?
Answer: Custom middleware can be used for various scenarios, such as logging, authentication, authorization,
error handling, request/response transformation, and more. For example, you might create custom logging
middleware to log request details for troubleshooting.
214. How does the ApplicationBuilder class relate to middleware in .NET Core?
Answer: The ApplicationBuilder class is used to build the request processing pipeline by adding middleware
components. Middleware components are added in the Configure method of the Startup class using the Use
extension methods.
215. What is the purpose of the next parameter in a middleware component's Invoke method?
Answer: The next parameter in a middleware component's Invoke method allows you to call the next middleware
in the pipeline. If you omit calling next, the pipeline will be short-circuited, and subsequent middleware won't be
executed.
216. What is the purpose of the Map and MapWhen methods in the ApplicationBuilder class?
Answer: The Map and MapWhen methods allow you to conditionally branch the request pipeline based on certain
criteria. Map maps a subpath to a branch of the pipeline, and MapWhen conditionally runs a branch of the pipeline
based on a predicate.
90
RESTRICTED
RESTRICTED
217. Explain the concept of endpoint routing in .NET Core. How does it relate to middleware?
Answer: Endpoint routing is a pattern for routing requests to different parts of your application. It's responsible
for mapping incoming requests to specific endpoints (controllers/actions) based on the route templates.
Middleware in ASP.NET Core can be configured to run before or after endpoint routing, allowing you to apply
processing logic at different stages of request handling.
220. How can you implement caching using middleware in .NET Core?
Answer: You can implement caching using middleware by creating custom middleware that checks whether the
requested resource is in the cache. If it's present, the middleware can return the cached response, otherwise, it
can pass the request down the pipeline, capture the response, and store it in the cache for future requests.
221. Explain the concept of short-circuiting the middleware pipeline. When and why would you use it?
Answer: Short-circuiting the middleware pipeline means stopping the execution of further middleware
components and immediately responding to the client. You might use this when you have specific conditions that
require an early response without going through the entire pipeline. For instance, you could use short-circuiting
for authentication checks to avoid processing unnecessary middleware for unauthorized requests.
222. Can you have middleware components within Razor Pages or MVC actions?
Answer: Yes, you can execute middleware components within Razor Pages or MVC actions by using the await
next.Invoke() call within the middleware's Invoke method. However, it's not a common practice, as middleware is
typically added to the pipeline using the Use methods in the Startup class.
223. How can you share dependencies, such as services, between different middleware components?
Answer: Middleware components can share dependencies through the HttpContext.RequestServices property,
which provides access to the application's dependency injection container. You can retrieve services from the
container using this property.
224. How would you handle streaming responses or large files in a middleware component?
Answer: Middleware can handle streaming responses by using the Response.Body stream. For large files, you
could use the TransmitFileAsync method or read/write chunks of data to the response stream while allowing the
application to be responsive.
225. What are the considerations when using middleware in a multithreaded environment?
91
RESTRICTED
RESTRICTED
Answer: Middleware components should be thread-safe since they might be executed concurrently by multiple
threads. Avoid using shared state within the middleware unless it's properly synchronized. If necessary, use
dependency injection to create new instances of services per request to avoid thread-safety issues.
226. How do you handle middleware ordering when using multiple routers, like MVC and Razor Pages?
Answer: Middleware order matters across routers. When using multiple routers, ensure that middleware affecting
routing is placed before the routers in the pipeline. Also, be cautious with the order of terminal middleware, as
they might affect the responses generated by the routers.
✓ Generic Host: The Generic Host is used for hosting non-HTTP services, such as background tasks, worker services,
and console applications. It's introduced in ASP.NET Core 3.0 and provides a consistent way to configure and run
background services using the same concepts as the web host. It's part of the Microsoft.Extensions.Hosting
namespace.
✓ Web Host: The Web Host is used for hosting ASP.NET Core web applications. It handles HTTP requests, routing,
middleware, and other web-related concerns. The Web Host is part of the Microsoft.AspNetCore.Hosting
namespace.
Both types of hosts share similar concepts, such as configuring services through dependency injection and setting up
application configuration. The host also manages the application's lifetime, including starting and stopping services.
229. What's the difference between a Generic Host and a Web Host in ASP.NET Core?
92
RESTRICTED
RESTRICTED
Answer: The Generic Host is used for hosting non-HTTP services like background tasks, while the Web Host is
specifically designed for hosting web applications with HTTP endpoints.
230. What namespace is commonly used for working with hosting in ASP.NET Core?
Answer: For the Generic Host, you use the Microsoft.Extensions.Hosting namespace. For the Web Host, you use
the Microsoft.AspNetCore.Hosting namespace.
231. How does the host handle dependency injection in ASP.NET Core?
Answer: The host's dependency injection container provides services that can be used throughout the application.
Services are registered during application startup using the ConfigureServices method.
233. What is the role of the application's lifetime managed by the host?
Answer: The application's lifetime includes startup, running, and graceful shutdown. The host manages the
sequence of these events and ensures that resources are properly released.
234. How can you customize the behavior of a host in ASP.NET Core?
Answer: You can customize the host's behavior by modifying the configuration, adding middleware, and
configuring services during the ConfigureServices method.
236. Can you host an ASP.NET Core web application without using the built-in hosting libraries?
Answer: Yes, you can self-host an ASP.NET Core application without using the built-in hosting libraries by directly
using Kestrel, the web server used by ASP.NET Core. However, using the built-in hosting libraries offers benefits
like integration with configuration, logging, and dependency injection.
237. How do you manage different environments (development, staging, production) in an ASP.NET Core application's
hosting?
Answer: ASP.NET Core provides an appsettings.json file that allows you to configure environment-specific settings.
By setting the ASPNETCORE_ENVIRONMENT environment variable, the application automatically loads the
appropriate configuration file. For example, setting it to "Staging" loads appsettings.Staging.json.
238. Is it possible to have multiple instances of the same ASP.NET Core application hosted on a single server?
Answer: Yes, you can host multiple instances of an ASP.NET Core application on the same server by using different
ports or hostnames. Each instance runs in its own process and has its own isolated environment.
239. How can you handle exception logging and reporting in an ASP.NET Core application hosted on a remote server?
Answer: You can use various logging providers available in ASP.NET Core, such as ILogger, and configure them to
log exceptions to a central location like a database or an external service. Additionally, you can integrate third-
party tools like Application Insights or Sentry for more advanced exception monitoring and reporting.
240. What is the purpose of the WebHostDefaults and HostDefaults classes in ASP.NET Core hosting?
93
RESTRICTED
RESTRICTED
Answer: These classes provide default configuration settings for the Web Host and the Generic Host, respectively.
They help standardize and simplify the configuration process by providing sensible defaults for various aspects of
the host, such as URLs, environment, and more.
241. Can you run both a Web Host and a Generic Host within the same ASP.NET Core application?
Answer: Yes, it's possible to run both a Web Host and a Generic Host within the same ASP.NET Core application.
This could be useful if your application includes both web-related components and background services.
242. How can you implement custom middleware to modify the request before it reaches the endpoint in an ASP.NET
Core application?
Answer: You can create custom middleware by implementing the IMiddleware interface or using the
UseMiddleware<T> extension method. Within the middleware, you can modify the request, perform custom logic,
and even short-circuit the request pipeline.
243. Explain the concept of in-process hosting and out-of-process hosting in ASP.NET Core.
Answer: In in-process hosting, the ASP.NET Core application is hosted within the same process as the host. This is
suitable for development scenarios. In out-of-process hosting, the application is hosted in a separate process,
which provides better isolation and reliability. Out-of-process hosting is used for production deployments.
244. What are the benefits and drawbacks of using Docker containers to host ASP.NET Core applications?
Answer: Benefits of using Docker containers include consistency in deployment, isolation, and portability across
different environments. However, drawbacks might include a slightly increased learning curve, potential resource
overhead, and the need for container orchestration tools for complex deployments.
Background Service: A Background Service is a lower-level concept that existed before Worker Services were
introduced. It's a more general approach for creating background tasks in .NET Core. While Worker Services provide a
higher level of abstraction and more built-in features, Background Services give you more flexibility in terms of
implementation.
94
RESTRICTED
RESTRICTED
To create a Background Service, you would typically inherit from the BackgroundService base class provided by the
Microsoft.Extensions.Hosting namespace. This base class includes methods like ExecuteAsync(CancellationToken
stoppingToken) that you override to implement your background task logic.
254. Can you run multiple instances of a Worker Service within the same application? If so, how would you manage
them?
95
RESTRICTED
RESTRICTED
Answer: Yes, you can run multiple instances of a Worker Service by registering them with different names in the
appsettings.json file and configuring a WorkerOptions section for each. This allows you to manage and control
multiple instances separately.
255. How can you implement periodic execution in a Worker Service without using built-in timers?
Answer: You can use a combination of await Task.Delay() and a loop within the ExecuteAsync method to
implement periodic execution. However, built-in timer libraries like System.Threading.Timer or
System.Timers.Timer are generally recommended for better accuracy and efficiency.
256. How can you ensure that a Background Service continues running even if an unhandled exception occurs within
its logic?
Answer: You can wrap the logic inside the ExecuteAsync method of the Background Service with a try-catch block.
Make sure to handle exceptions appropriately, log them, and continue the execution of the loop or task.
Globalization:
✓ Resource Files: Externalize user-visible strings, messages, and other localized content into resource files.
In .NET, these are typically .resx files.
✓ Culture-Neutral Code: Write code in a culture-neutral manner. Avoid hardcoding culture-specific formats,
such as date and number formats.
✓ Culture-Aware APIs: Use culture-aware APIs when working with dates, times, numbers, and strings. These
APIs automatically format and parse values based on the user's culture.
✓ Use Resource Managers: Utilize the ResourceManager class to access resources based on the user's
culture. This ensures that the correct localized content is displayed.
Localization:
Culture-Specific Resource Files: Create separate resource files for each target culture. For example, Resources.resx
for default content and Resources.fr.resx for French content.
✓ Set Current Culture: Set the application's Thread.CurrentThread.CurrentCulture and
Thread.CurrentThread.CurrentUICulture to the desired culture. This controls how dates, numbers, and
strings are formatted and displayed.
✓ Localized Content: Load and display content from the appropriate culture-specific resource file based on
the user's chosen culture.
✓ Formatting and Parsing: Utilize culture-aware APIs to format and parse dates, times, and numbers in a
way that's appropriate for the user's culture.
✓ Testing: Thoroughly test your localized application with different cultures to ensure that content is
correctly displayed and formatted.
96
RESTRICTED
RESTRICTED
97
RESTRICTED
RESTRICTED
SignalR is a real-time communication library in .NET Core that enables bi-directional communication between the
server and connected clients over websockets or other supported transport mechanisms. It's particularly useful
for building interactive and dynamic web applications, online games, chat applications, live data visualization, and
more.
Key Concepts:
✓ Hubs: Hubs are high-level abstractions in SignalR that provide a simple way to manage communication
between clients and the server. They allow you to call methods on connected clients from the server and
vice versa.
✓ Connections: Connections represent a communication channel between a client and the server. Each
client maintains a connection to the server, enabling real-time communication.
✓ Clients: Clients are JavaScript or .NET Core code that connect to the SignalR hub. They can receive
messages and invoke methods on the server.
Features:
✓ Real-Time Communication: SignalR enables real-time updates and notifications, making it suitable for
applications requiring instant data synchronization.
✓ Multiple Transport Support: SignalR supports various transport mechanisms, including WebSockets,
Server-Sent Events (SSE), and Long Polling. It uses the most suitable transport based on the client's
capabilities.
✓ Scalability: SignalR supports scaling out across multiple servers or processes, making it suitable for high-
traffic scenarios.
✓ Automatic Reconnection: SignalR clients automatically attempt to reconnect to the server if the
connection is lost, providing a seamless experience for users.
✓ Authorization and Security: SignalR provides mechanisms for securing connections and methods to ensure
that only authorized clients can access certain functionality.
Integration with .NET Core:
✓ Installing SignalR: To use SignalR in a .NET Core application, you need to install the
Microsoft.AspNetCore.SignalR NuGet package.
✓ Creating Hubs: Define SignalR hubs by creating classes that derive from the Hub class. These classes
contain methods that can be invoked by clients.
✓ Configuring Endpoints: Configure SignalR endpoints in the Startup.cs file to specify how clients connect to
the hub.
✓ Client-Side Integration: On the client side, you can use JavaScript libraries for web applications or the
Microsoft.AspNetCore.SignalR.Client NuGet package for .NET Core clients.
Use Case:
SignalR is ideal for scenarios that require real-time updates and user interactions, such as:
✓ Chat applications
✓ Collaborative tools
✓ Multiplayer online games
✓ Live data dashboards
✓ Notifications and alerts
✓ Live customer support
98
RESTRICTED
RESTRICTED
273. How does SignalR handle automatic reconnection when a client loses its connection?
Answer: SignalR clients automatically attempt to reconnect to the server if the connection is lost, ensuring a
continuous and seamless user experience.
274. What is the purpose of the [Authorize] attribute in SignalR hubs?
Answer: The [Authorize] attribute in SignalR hubs restricts access to methods based on user authentication and
authorization, ensuring that only authorized clients can invoke specific methods.
275. How can you handle communication between specific clients using SignalR?
Answer: SignalR provides group communication functionality, allowing you to organize clients into groups and
send messages to specific groups of clients.
276. How do you integrate SignalR with JavaScript in a web application?
Answer: In a web application, you can use the SignalR JavaScript client library to connect to the SignalR hub and
receive real-time updates from the server.
277. Can you briefly explain how to scale a SignalR application to handle high traffic?
Answer: To scale a SignalR application, you can use a backplane, such as Azure SignalR Service or Redis, to
distribute messages and manage connections across multiple servers or processes.
278. What are some potential challenges or considerations when using SignalR?
Answer: Challenges include managing state synchronization between server and clients, handling connection
timeouts and retries, and ensuring efficient use of server resources.
279. In what scenarios would you choose SignalR over traditional HTTP-based communication?
Answer: SignalR is beneficial for scenarios requiring real-time updates, interactive user experiences, and
collaborative features, such as chat applications, live data dashboards, and online gaming.
280. What are the steps to enable cross-platform communication between a .NET Core SignalR server and a JavaScript
client?
Answer: To enable cross-platform communication, use the SignalR JavaScript client library on the client side and
the Microsoft.AspNetCore.SignalR.Client package on the .NET Core server side.
99
RESTRICTED
RESTRICTED
281. In a load-balanced environment, what strategies can you use to ensure that SignalR clients are connected to the
same server instance?
Answer: To ensure that SignalR clients stay connected to the same server instance, you can use a backplane
solution like Redis, which shares state across multiple server instances.
282. What are the benefits of using the SendAsync method over the InvokeAsync method in SignalR?
Answer: The SendAsync method is used when you want to broadcast a message to all connected clients without
waiting for a response. In contrast, the InvokeAsync method is used when you want to invoke a method on a
specific client and await a response.
283. What are the steps to enable cross-platform communication between a .NET Core SignalR server and a JavaScript
client?
Answer: To enable cross-platform communication, use the SignalR JavaScript client library on the client side and
the Microsoft.AspNetCore.SignalR.Client package on the .NET Core server side.
286. How can you create a new ASP.NET Core Web API project?
Answer: You can create a new ASP.NET Core Web API project using the dotnet new webapi command or by
selecting the "ASP.NET Core Web API" template in Visual Studio.
287. How can you return JSON data from a Web API controller action in ASP.NET Core?
Answer: You can return JSON data by using the return Json(data) method or by using the return Ok(data)
method, where data is the object you want to serialize.
288. What is the purpose of the [HttpGet], [HttpPost], etc. attributes in Web API controllers?
Answer: These attributes are used to specify the HTTP verb (GET, POST, etc.) that an action method responds to.
They define the type of HTTP request the action handles.
289. How can you bind data from the request body in a Web API action method?
Answer: Data from the request body can be bound to method parameters or model properties using the
[FromBody] attribute, like [HttpPost] public IActionResult Post([FromBody] MyModel model).
290. How can you handle errors and return appropriate status codes in a Web API action?
100
RESTRICTED
RESTRICTED
Answer: You can return status codes using methods like return BadRequest(), return NotFound(), or return
StatusCode(). You can also create custom error responses.
291. What is the purpose of the [FromBody] and [FromQuery] attributes in Web API action methods?
Answer: The [FromBody] attribute binds data from the request body, while the [FromQuery] attribute binds data
from the query string. They are used to extract data for parameter binding.
292. How can you implement authentication and authorization in ASP.NET Core Web API?
Answer: Authentication and authorization can be implemented using middleware like JWT (JSON Web Tokens),
OAuth, or OpenID Connect. The [Authorize] attribute can be used to restrict access to authorized users.
293. How can you return specific HTTP status codes and custom error messages from a Web API action?
Answer: Specific HTTP status codes and custom error messages can be returned using methods like
BadRequest(), NotFound(), and StatusCode(), along with custom error model classes.
295. What are the differences between Web API and WCF REST API?
Answer: Web API is suitable for HTTP-based services, while WCF REST API is ideal for Message queues, one-way
messaging, and duplex communication. WEB API supports any media format, even XML and JSON, while WCF
supports SOAP and XML formats. ASP.Net Web API is ideal for building HTTP services, while WCF is perfect for
developing service-oriented applications. To run Web API, there is no configuration required, while in the case of
WCF, a lot of configuration is required to run it.
296. What are the several return types in ASP.Net Web API?
Answer: The various return types in ASP.Net Web API are:
✓ IHttpActionResult
✓ HttpResponseMessage
✓ Void
✓ Other Type – string, int, or other entity types.
297. How to secure an ASP.Net Web API?
Answer: To secure an ASP.Net Web API, we need to control the Web API and decide who can access the API and
who cannot access it. Web API can be accessed by anyone who knows about the URL.
101
RESTRICTED
RESTRICTED
Answer: It is an approach to secure .Net Web API as it authenticates users by a signed token, also called a token-
based approach.
305. What are the HTTP methods commonly used in RESTful APIs?
Common HTTP methods used are GET (retrieve data), POST (create data), PUT (update data), and DELETE
(remove data).
306. What is the role of media types (MIME types) in RESTful APIs?
Media types indicate the format of the data being sent or received. Common types include JSON
(application/json) and XML (application/xml).
102
RESTRICTED
RESTRICTED
Answer: The default media types that are supported by Web API are XML, form-urlencoded data, JSON, BSON.
The other media types supported can be done by writing a media formatter.
311. How to implement Basic Authentication in ASP.Net Web API?
Answer: Basic Authentication in ASP.Net Web API is one where the client will send a request using the word
Basic with an Authorization header, followed by a base 64 encoded string.
315. Are the HTML tags and elements the same thing?
No. HTML elements are defined by a starting tag, may contain some content and a closing tag.For example,
<h1>Heading 1</h1> is a HTML element but just <h1> is a starting tag and </h1> is a closing tag.
103
RESTRICTED
RESTRICTED
318. In how many ways can we specify the CSS styles for the HTML element?
There are three ways in which we can specify the styles for HTML elements:
✓ Inline: Here we use the ‘style’ attribute inside the HTML element.
✓ Internal: Here we use the <style> tag inside the <head> tag. To apply the style we bind the elements
using ‘id’ or ‘class’ attributes.
✓ External: Here we use the <link> tag inside <head> tag to reference the CSS file into our HTML code.
Again the binding between elements and styles is done using ‘id’ or ‘class’ attributes.
319. Difference between link tag <link> and anchor tag <a>?
The anchor tag <a> is used to create a hyperlink to another webpage or to a certain part of the webpage and
these links are clickable, whereas, link tag <link> defines a link between a document and an external resource
and these are not clickable.
<form action="/submit_data.php">
<label>Enter your name: </label>
<input type="text" name="name" />
<label>Enter Mobile number </label>
<input type="number" name="mobile_no"/>
<input type="submit" value="Submit">
</form>
321. What are some of the advantages of HTML5 over its previous versions?
Some advantages of HTML5 are:-
104
RESTRICTED
RESTRICTED
Web Storage API (localStorage and sessionStorage) allows storing key-value pairs in a user's browser for
persistent and session-based data storage.
327. How can I include HTML5 input types in ASP.NET Core forms?
ASP.NET Core's HtmlHelper methods enable you to generate HTML5 input types like email, url, and number
within your Razor views.
328. How does ASP.NET Core handle responsive design using HTML5?
ASP.NET Core can be combined with CSS3 and media queries to create responsive layouts that adapt to different
screen sizes and devices.
329. How can we use HTML5's <canvas> element in ASP.NET Core?
We can integrate HTML5's <canvas> element within your Razor views to create dynamic graphics and
animations directly in the browser.
330. Is HTML5's offline storage feature compatible with ASP.NET Core?
Yes, you can utilize HTML5's offline storage features like Application Cache in combination with ASP.NET Core to
create offline-capable web applications.
331. What is the usage of a novalidate attribute for the form tag that is introduced in HTML5?
Its value is a boolean type that indicates whether or not the data being submitted by the form will be validated
beforehand. By making this false, forms can be submitted without validation which helps users to resume later
also.
105
RESTRICTED
RESTRICTED
✓ Inline CSS: It is used when less amount of styling is needed or in cases where only a single element has
to be styled. To use inline styles add the style attribute in the relevant tag.
✓ External Style Sheet: This is used when the style is applied to many elements or HTML pages. Each
page must link to the style sheet using the <link> tag.
✓ Internal Style Sheet: It is used when a single HTML document has a unique style and several elements
need to be styled to follow the format. Internal styles sheet is added in the head section of an HTML
page, by using the <style> tag.
338. How do you add JavaScript to an HTML webpage?
To add JavaScript to an HTML webpage:
✓ Inline JavaScript:
Place JavaScript code directly within <script> tags in the HTML file's <head> or <body> section.
<script>
// Your JavaScript code here
</script>
✓ External JavaScript File:
Create a separate .js file and link it using the <script> tag's src attribute.
<script src="your-script.js"></script>
✓ Document Ready Event (Recommended):
Sample Questionnaires on CSS:
✓ Separation of content from presentation - CSS provides a way to present the same content in multiple
presentation formats in mobile or desktop or laptop.
✓ Easy to maintain - CSS, built effectively can be used to change the look and feel complete by making
small changes. To make a global change, simply change the style, and all elements in all the web pages
will be updated automatically.
106
RESTRICTED
RESTRICTED
✓ Bandwidth - Used effectively, the style sheets will be stored in the browser cache and they can be
used on multiple pages, without having to download again.
341. How to include CSS in the webpage?
There are different ways to include a CSS in a webpage:
✓ External Style Sheet: An external file linked to your HTML document: Using link tag, we can link the style
sheet to the HTML page.
<link rel="stylesheet" type="text/css" href="mystyles.css" />
✓ Embed CSS with a style tag: A set of CSS styles included within your HTML page.
<style type="text/css">
/*Add style rules here*/
</style>
✓ Add inline styles to HTML elements(CSS rules applied directly within an HTML tag.): Style can be added
directly to the HTML element using a style tag.
<h2 style="color:red;background:black">Inline Style</h2>
✓ Import a stylesheet file (An external file imported into another CSS file): Another way to add CSS is by
using the @import rule. This is to add a new CSS file within CSS itself.
@import "path/to/style.css";
107
RESTRICTED
RESTRICTED
It is a string that identifies the elements to which a particular declaration apply. It is also referred as a link
between the HTML document and the style sheet. It is equivalent of HTML elements. There are several different
types of selectors in CSS: -
108
RESTRICTED
RESTRICTED
@media print {
h2 {
background-color: blue;
}
}
109
RESTRICTED
RESTRICTED
function function_name(){
//function body
}
110
RESTRICTED
RESTRICTED
✓ String: The string data type represents a sequence of characters. It is written within quotes and can be
represented using a single or a double quote.
✓ Number: The number data type is used to represent numeric values and can be written with or without
decimals.
Example: var x = 5; //without decimal
✓ Boolean: The Boolean data type is used to represent a Boolean value, either false or true. This data type
is generally used for conditional testing.
Example: var x = 5;
console.log(number('1000'));
111
RESTRICTED
RESTRICTED
form.addEventListener("submit", function(event) {
event.preventDefault();
if (!isValidEmail(emailInput.value)) {
alert("Invalid email format");
return;
}
112
RESTRICTED
RESTRICTED
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
113
RESTRICTED
RESTRICTED
✓ As it is developed using JavaScript language, it has all features that JavaScript has, with multiple inbuilt
methods it is easy to use for validation
✓ Event handling is one of the good features of jQuery
✓ It’s easy to apply CSS to the controls using jQuery
✓ jQuery has good support to AJAX.
✓ jQuery has good support to animations as well.
114
RESTRICTED
RESTRICTED
A: You can include jQuery by adding a script tag with a link to the jQuery library in the <head> or <body> section
of your HTML document. For example:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
381. How can you change the text content of an element using jQuery?
A: You can use the .text() method to set or get the text content of an element. For example:
$.ajax({
url: "https://api.example.com/data",
method: "GET",
success: function(response) {
console.log(response);
},
error: function(error) {
console.error(error);
}
});
384. How can you add or remove CSS classes from an element using jQuery?
A: You can use the .addClass() method to add a class, .removeClass() method to remove a class, and
.toggleClass() method to toggle a class on an element.
115
RESTRICTED
RESTRICTED
385. What is the difference between .html() and .text() methods in jQuery?
A: The .html() method sets or gets the HTML content of an element, including any HTML tags. The .text() method
sets or gets only the text content of an element, without any HTML tags.
$("div").animate({
width: "200px",
height: "200px"
}, 1000); // Animates div to 200x200px over 1 second
$("p")
.addClass("highlight")
.text("Updated text")
.fadeOut();
$("button").click(function() {
alert("Button clicked!");
});
391. What is the difference between .prop() and .attr() methods in jQuery?
A: The .prop() method gets the value of a property, such as a boolean attribute, from the first matched element.
The .attr() method gets the value of an attribute for the first matched element. Generally, .prop() is used for
properties that can have true/false values, while .attr() is used for other HTML attributes.
116
RESTRICTED
RESTRICTED
392. What is the purpose of the $.get() and $.post() methods in jQuery?
A: The $.get() method is used to perform an HTTP GET request, and the $.post() method is used to perform an
HTTP POST request. These methods are shorthand for the $.ajax() function, specifically tailored for these HTTP
methods.
395. How do you ensure that your jQuery code executes after the DOM is fully loaded in ASP.NET Core?
A: You can use the $(document).ready() function to ensure that your jQuery code executes after the DOM is fully
loaded. Alternatively, you can use the shorthand version $(function() { /* your code here */ });.
396. How can you make an AJAX request using jQuery in ASP.NET Core?
A: You can use the $.ajax() function to make AJAX requests in ASP.NET Core. You specify the URL, type of request
(GET, POST, etc.), and handle the success or error callbacks. Make sure to provide the appropriate URL route
using Razor syntax.
397. How do you handle errors in AJAX requests with jQuery in ASP.NET Core?
A: You can handle errors in AJAX requests using the error callback of the $.ajax() function. This callback will be
invoked if the request encounters an error, such as a network issue or a server-side error.
We know cache is the temp memory that store data, each time when access any page it accesses cache and load
data from there only, it will boost application performance, the same concept applies to jQuery we can cache
jQuery elements and use them instead of re-querying or re-executing methods/property on DOM
✓ text()
✓ html()
117
RESTRICTED
RESTRICTED
✓ val()
400. What is the difference between “this” and “$(this)” In jQuery?
A: To refer current element, we use ‘this’ element, in traditional, we use ‘this’ object and in jQuery, we use
‘$(this)’ this new object will also help us to explore and support jQuery methods also. No doubt you can use
‘this’ in jQuery also. Look at below sample
//Using ‘this’
$(document).ready(function () {
$('#id1').click(function () {
alert(this.innerText);
});
});
//Using $(this)
$(document).ready(function () {
$('# id1').click(function () {
alert($(this).text());
});
✓ Get()
✓ Post()
✓ GetJSON()
✓ Ajax()
402. What is the difference between $(window).load and $(document).ready function in jQuery?
A: $(window).load is an event that fires when the DOM and all the content (everything) on the page is fully
loaded. This event is fired after the ready event.
<script type="text/javascript" lang="ja">
$(window).load(function() {
alert("Window load event fired");
});
$(document).ready(function() {
alert("document ready event fired");
});
</script>
118
RESTRICTED
RESTRICTED
$.ajax () Method
JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:
Both of the preceding approaches are kind of static declarations. Now let's do some dynamic programming with
Arrays.
$('#txtName')
$(document).ready(function(){
});
Over here $ sign can be replaced with "jQuery" keyword.
119
RESTRICTED
RESTRICTED
jQuery(document).ready(function(){
});
We can have more than one document.ready() function in a page where we can have only one body onload
function.
document.ready() function is called as soon as DOM is loaded where body.onload() function is called when
everything gets loaded on the page that includes DOM, images and all associated resources of the page.
410. What is the difference between eq() and get() methods in jQuery?
A: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element
within that set and returns it. That means that you can use jQuery functions on it.
get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is
a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used.
120
RESTRICTED