Difference between Stack and Heap Memory in C#
Category Stack Memory Heap Memory
It is an array of memory.
It is an area of memory
where chunks are allocated
What is Stack & It is a LIFO (Last In First to store certain kinds of data
Heap? Out) data structure. objects.
In it data can be added In it data can be stored and
to and deleted only from removed in any order.
the top of it.
How Memory is
Manages?
Practical Scenario
Value of variable storing Value of variable storing in
in stack heap
"Things" declared with
"Things" declared with
the following list of type
following list of type
declarations are Value
declarations are Reference
Types
Types
What goes on Stack (because they are from (and inherit from
& Heap? System.ValueType):
System.Object... except, of
bool, byte, char, course, for object which is
decimal, double, enum, the System.Object object):
float, int, long, sbyte,
class, interface, delegate,
short, struct, uint, ulong,
object, string
ushort
Memory Allocation Memory allocation is Static Memory allocation is Dynamic
How is it Stored? It is stored Directly It is stored indirectly
Is Variable Resized? Variables can’t be Resized Variables can be Resized
Access Speed Its access is fast Its access is Slow
Its block allocation is
reserved in LIFO.
How is the Block Its block allocation is free and
Allocated? The most recently done at any time
reserved block is always
the next block to be
freed.
It can be visible/accessible
Visibility or It can be visible/accessible to all
only to the Owner of
Accessibility the threads
Thread
In recursion calls memory In recursion calls memory filled
In Recursion Calls?
fills up quickly up slowly
It can be used by one It can be used by all the parts of
Used By?
thread of execution the application
.NET Runtime throws
exception
StackOverflowExcept
“StackOverflowException” -
ion
when stack space is
exhausted
Local variables get
When wiped off? wiped off once they lose -
the scope
Contains It contains values for -
Integral Types, Primitive
Types and References to
the Objects
It is a special thread created
by .NET runtime to monitor
allocations of heap space.
Garbage Collector -
It only collects heap memory
since objects are only
created in heap
Exception Handling in dotnet
For ASP.NET Core MVC, we have similar situation or discussion, but, with
major differences:
1. We will not discuss the Try-Catch-Finally approach, because it is language
related issue;
2. Due to Exception Filter, the approach is just secondary importance in
ASP.NET Core app, we will just make brief discussion at the end.
This will be the order inwhich we will discuss the topic today:
A: Exception Handling in Development Environment for ASP.NET Core MVC
o UseDeveloperExceptionPage
B: Exception Handling in Production Environment for ASP.NET Core MVC
o Approach 1: UseExceptionHandler
1: Exception Handler Page
2: Exception Handler Lambda
o Approach 2: UseStatusCodePages
1: UseStatusCodePages, and with format string, and with Lambda
2: UseStatusCodePagesWithRedirects
3: UseStatusCodePagesWithReExecute
o Approach 3: Exception Filter
Local
Global
A: Exception Handling in Developer Environment
The ASP.NET Core starup templates generate the following code,
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
......
}
C#
Copy
The UseDeveloperExceptionPage extension method adds middleware into
the request pipeline. The Developer Exception Page displays developer
friendly detailed information about request exceptions. This helps
developers in tracing errors that occur during development phase.
As this middleware displays sensitive information, it is advisable to add it
only in development environment. The developer environment is a new
feature in .NET Core.
New Way: IExceptionHandler
ASP.NET Core 8 introduces a new IExceptionHandler abstraction for
managing exceptions. The built-in exception handler middleware
uses IExceptionHandler implementations to handle exceptions.
This interface has only one TryHandleAsync method.
TryHandleAsync attempts to handle the specified exception within the
ASP.NET Core pipeline. If the exception can be handled, it should
return true. If the exception can't be handled, it should return false. This
allows you to implement custom exception-handling logic for different
scenarios.
Here's a GlobalExceptionHandler implementation:
internal sealed class GlobalExceptionHandler :
IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler>
_logger;
public
GlobalExceptionHandler(ILogger<GlobalExceptionHandler>
logger)
{
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
_logger.LogError(
exception, "Exception occurred:
{Message}", exception.Message);
var problemDetails = new ProblemDetails
{
Status =
StatusCodes.Status500InternalServerError,
Title = "Server error"
};
httpContext.Response.StatusCode =
problemDetails.Status.Value;
await httpContext.Response
.WriteAsJsonAsync(problemDetails,
cancellationToken);
return true;
}
}
Configuring IExceptionHandler Implementations
You need two things to add an IExceptionHandler implementation to the
ASP.NET Core request pipeline:
1. Register the IExceptionHandler service with dependency injection
2. Register the ExceptionHandlerMiddleware with the request pipeline
You call the AddExceptionHandler method to register
the GlobalExceptionHandler as a service. It's registered with a singleton
lifetime. So be careful about injecting services with a different lifetime.
I'm also calling AddProblemDetails to generate a Problem Details response
for common exceptions.
builder.Services.AddExceptionHandler<GlobalExceptionHa
ndler>();
builder.Services.AddProblemDetails();
You also need to call UseExceptionHandler to add
the ExceptionHandlerMiddleware to the request pipeline:
app.UseExceptionHandler();
Chaining Exception Handlers
You can add multiple IExceptionHandler implementations, and they're called
in the order they are registered. A possible use case for this is using
exceptions for flow control.
You can define custom exceptions
like BadRequestException and NotFoundException. They correspond with the
HTTP status code you would return from the API.
Here's a BadRequestExceptionHandler implementation:
internal sealed class BadRequestExceptionHandler :
IExceptionHandler
{
private readonly
ILogger<BadRequestExceptionHandler> _logger;
public
GlobalExceptionHandler(ILogger<BadRequestExceptionHand
ler> logger)
{
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
if (exception is not BadRequestException
badRequestException)
{
return false;
}
_logger.LogError(
badRequestException,
"Exception occurred: {Message}",
badRequestException.Message);
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Bad Request",
Detail = badRequestException.Message
};
httpContext.Response.StatusCode =
problemDetails.Status.Value;
await httpContext.Response
.WriteAsJsonAsync(problemDetails,
cancellationToken);
return true;
}
}
And here's a NotFoundExceptionHandler implementation:
internal sealed class NotFoundExceptionHandler :
IExceptionHandler
{
private readonly ILogger<NotFoundExceptionHandler>
_logger;
public
GlobalExceptionHandler(ILogger<NotFoundExceptionHandle
r> logger)
{
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
if (exception is not NotFoundException
notFoundException)
{
return false;
}
_logger.LogError(
notFoundException,
"Exception occurred: {Message}",
notFoundException.Message);
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status404NotFound,
Title = "Not Found",
Detail = notFoundException.Message
};
httpContext.Response.StatusCode =
problemDetails.Status.Value;
await httpContext.Response
.WriteAsJsonAsync(problemDetails,
cancellationToken);
return true;
}
}
You also need to register both exception handlers by
calling AddExceptionHandler:
builder.Services.AddExceptionHandler<BadRequestExcepti
onHandler>();
builder.Services.AddExceptionHandler<NotFoundException
Handler>();
The BadRequestExceptionHandler will execute first and try to handle the
exception. If the exception isn't handled, NotFoundExceptionHandler will
execute next and attempt to handle the exception.
Takeaway
Using middleware for exception handling is an excellent solution in
ASP.NET Core. However, it's great that we have new options using
the IExceptionHandler interface. I will use the new approach in ASP.NET
Core 8 projects.
(1) What is difference between reflection and dependency injection 🤔?
(2)What is difference between filter and service in angular J's 🤔 ?
(3)What are derectives in angular J's ?
(4)Have u used jquery with angular J's ?🤔
(5)Why MVC when we already have multi tier architecture 😴?
(6)What is route in angular js🤔?
(7)how to implement security in basichttpbindinding ?
(8)
(9)
(10)
Difference between Webservice and WCF Service
ASP.NET Web Service WCF
WebService and WebMethod ServiceContract and
attributes are used for defining OperationContract attributes are
web service. used for defining WCF service.
Supports only HTTP, HTTPS Supports various protocols like
protocols. HTTP, HTTPS, TCP, Named Pipes
and MSMQ.
Hosted only in IIS. Hosted in IIS, WAS (Windows
Activation Service), Self-hosting,
Windows Service.
Support security but is less Supports security, reliable
secure as compared to WCF. messaging, transaction and AJAX
and REST supports.
Supports XML serializer by using Supports DataContract serializer
System.Xml.Serialization. by using
System.Runtime.Serialization.
Supports One-Way and Request- Supports One-Way, Request-
Response service operations. Response and Duplex service
operations.
WCF are faster than Web
Web Services are slower than Services.
WCF
Hash Table cannot be serialized. Hash Table can be serialized.
It can serializes only those
collections which
implement IEnumerable and
ICollection.
Unhandled Exceptions returns to Unhandled Exceptions does not
the client as SOAP faults. return to the client as SOAP
faults. WCF supports better
exception handling by using
FaultContract.
Supports XML and MTOM Supports XML, MTOM, Binary
(Message Transmission message encoding.
Optimization Mechanism)
message encoding.
Supports multi-threading by
Doesn’t support multi-threading. using ServiceBehaviour class.
Sr. Key Delete Truncate
No.
1 Basic It is used to delete specific data It is used to delete the entire dat
of the table
2 Where We can use with where clause It can’t be used with where clause
Sr. Key Delete Truncate
No.
clause
3 Locking It locks the table row before It locks the entire table
deleting the row
4 Rollback We can rollback the changes. We can’t rollback the changes
5 Performance It is slower than truncate It is faster than delete
6 Does not reset the identity of the Resets identity of Table
table
7 Its DML Command Its DDL Command
8 Where Where condition can be used Where condition cant be used
3
Access Specifiers C#
Class : Internal
Methods : private
Interface , enum : public
The default accessibility of top-level types is internal.
The default accessibility of class and struct members is private.
The only possible accessibility of interface and enum members is public.
Cache busting
Cache busting in ASP.NET Core is a technique that forces a browser to
download the latest version of a file from a server instead of using a cached
version. This is important for ensuring that users see the most up-to-date
version of a website or application.
Here's how cache busting works:
A unique identifier, like a version number or timestamp, is appended to the file's
URL.
The browser treats the file as a new resource and fetches the most recent version.
When the browser makes a request for the file again, it will get the new version from
the server instead of using the cached version.
Some techniques for implementing cache busting include: query string
parameters, file name versioning, and file path versioning.
1. What’s the difference
between .NET and .NET
Framework?
.NET is an open-source, cross-platform framework with core
libraries (in NuGet packages) for building modern, cloud-
based, and microservices-based applications. It supports
development on Linux, macOS, and Windows and provides a
modular lightweight runtime deployed as a self-contained
executable or a shared library.
.NET Framework, on the other hand, is a Windows-only
framework for developing classes and libraries and running
code on web services and traditional desktop applications. It
provides a larger set of libraries and features than .NET Core,
but it’s limited to Windows and is not open-source.
2. How does ASP.NET
Core handle
dependency injection?
Dependency injection is a design pattern of ASP.NET Core
that’s handled by the built-in dependency injection container.
This container can register and resolve dependencies,
typically defined as interfaces implemented by concrete
classes.
There are several ways to configure the container, including
the ConfigureServices method in the Startup class (the entry
point of a .NET application), attributes on classes and
properties, and the service provider itself. ASP.NET Core
supports constructor, property, and method injection,
allowing dependencies to be dynamically injected into
methods at runtime.
However, a more up-to-date way to handle dependency
injection in ASP.NET Core focuses on singleton, transient, and
scoped service lifetimes. You can read more about this here.
3. What is Kestrel and
how does it differ from
IIS?
Kestrel is a cross-platform, lightweight web server used by
default in ASP.NET Core applications. It can run on Linux,
macOS, and Windows and provides a fast, scalable, and
efficient platform for handling HTTP requests.
Kestrel is designed to be used with a reverse proxy server,
such as IIS or Nginx, which handles load balancing and SSL
termination tasks.
On the other hand, IIS is a web server specific to Windows
that provides more advanced features than Kestrel, such as
support for HTTP/2 and WebSocket protocols and integration
with Windows authentication and SSL.
4. What is the purpose
of middleware in
ASP.NET Core?
Middleware in ASP.NET Core is a software component
responsible for processing requests and generating
responses in the web application pipeline. It sits between the
server side and the application and is designed to handle
cross-cutting concerns, such as authentication, caching,
logging, and routing.
The primary purpose of middleware is to provide a modular
way of processing HTTP requests and responses, allowing
developers to add, remove, or reorder middleware
components in the pipeline based on their specific needs.
This makes it easy to customize the web application's
behavior without modifying the core application logic.
5. How does ASP.NET
Core handle garbage
collection?
Garbage collection in ASP.NET Core automatically manages
the allocation and deallocation of memory that an ASP.NET
Core application uses. The garbage collector is responsible
for identifying and reclaiming memory no longer needed by
the application, thus freeing up resources and improving the
application's performance.
The garbage collector in ASP.NET Core uses a generational
garbage collection algorithm that divides the heap into gen0,
gen1, and gen2, each generation representing a different
stage of the object's life cycle. New objects are allocated to
the youngest generation, and as they survive longer, they
are moved to older generations. The garbage collector
collects and frees memory from the youngest generation first
and only collects the older generations when necessary.
ASP.NET Core provides several options for configuring and
tuning the garbage collector, including setting the maximum
size of the heap, the size of the individual generations, and
the frequency of garbage collection. These options can be
configured using environment variables or application
configuration files depending on the needs of the application.
In addition, ASP.NET Core provides several tools and APIs for
monitoring and diagnosing garbage collection behavior,
including the GC.Collect() method, which can force a
garbage collection cycle, and
the GC.GetTotalMemory() method, which returns the total
amount of memory used by the application.
Overall, garbage collection in ASP.NET Core is a critical
component of the runtime, ensuring efficient memory use
and improving the performance and stability of ASP.NET Core
applications.
8. How can you
implement background
work in an ASP.NET Core
application?
The IHostedService interface in ASP.NET Core defines a
background task or service as part of the application's
lifetime. It’s typically used for monitoring, logging, or data
processing tasks that must run continuously, even when the
application is not processing requests. Classes that
implement the IHostedService interface are added to the
application's service collection using dependency injection,
and they are started and stopped automatically by the
application's host.
The IHostedService interface defines two methods:
StartAsync and StopAsync. The StartAsync method is called
when the application starts and is used to start the
background task or service. The StopAsync method is called
when the application is stopped or restarted. It’s used to stop
the background task or service, releasing acquired resources.
10. How do you
implement caching in
ASP.NET Core?
Response caching in ASP.NET Core is a technique used to
improve the performance and scalability of web applications
by caching the ASP.NET Core MVC responses returned by the
server for a specific period. Caching the response can help
reduce the number of requests made to the server, as clients
can reuse the cached response instead of requesting the
same resource again.
Response caching works by adding a caching layer between
the client and the server. When a client requests a resource,
the caching layer checks whether the response for the
request has been cached. If the response is cached, the
caching layer returns the cached response to the client. If the
response is not cached, the request is forwarded to the
server, and the server generates the response and caches it
for future use.
In ASP.NET Core, response caching can be implemented
using the [ResponseCache] attribute, which can be applied to
an action method in a controller. The attribute allows
developers to specify the caching behavior, such as the
duration of the cache, the location of the cache, and the
cache key. By default, the caching location is on the client
side, but it can also be set to a distributed or proxy cache
depending on the needs of the application.
11. What’s the
difference between
middleware and a filter
in ASP.NET Core?
In ASP.NET Core, middleware and filters are two mechanisms
used for processing requests and responses.
Middleware is a software component between the web server
(like Apache) and the application and processes requests and
responses during the application development. Middleware
can be used for various tasks, such as authentication,
logging, and error handling. Middleware is executed in a
pipeline, and each middleware component can modify the
request or response before passing it to the next component
in the pipeline.
Conversely, filters are used to perform cross-cutting concerns
on controllers and actions in an MVC application. Filters can
be used for authorization, validation, and caching tasks.
Filters are executed before and after the action method, and
they can modify the request or response or short-circuit the
request processing if necessary.
The main difference between middleware and filters is their
scope and the way they are executed. Middleware is
executed globally and can be used for any request or
response. In contrast, filters are executed only for specific
controllers or actions and can be used to modify the request
or response before or after the action method.
12. What is Core CLR?
CoreCLR (Common Language Runtime, now renamed to .NET
Runtime) is the runtime environment executing ASP.NET Core
applications. It is the open-source implementation of the .NET
runtime, developed by Microsoft and available on multiple
platforms, including Windows, Linux, and macOS.
CoreCLR provides a managed execution environment for
ASP.NET Core applications, including memory management,
garbage collection, type safety, and security. It also supports
just-in-time (JIT) compilation, which compiles code at runtime
to native machine code, allowing for faster execution.
CoreCLR is designed to be modular, with various components
such as the garbage collector, JIT compiler, and primitive
data type system implemented as separate modules. This
modularity allows for more flexibility and customization in
building and deploying .NET Core applications.
CoreCLR is a critical component of the .NET platform,
providing the necessary runtime infrastructure for developing
and executing .NET applications across different platforms.
2. Explain the key differences between ASP.NET
Core and ASP.NET.
Key differences between ASP.NET Core and ASP.NET
Feature ASP.NET Core ASP.NET
Cross-platform (Windows, Linux,
Platform Windows only
macOS)
Framework Size Modular and lightweight Larger and more comple
Generally faster and more
Performance Potentially slower due to
efficient
Architecture Built on .NET Core runtime Built on full .NET Frame
Model-View- Integrated with Web API in a Separate MVC framewo
Controller (MVC) unified framework API
Complex and
Configuration More flexible and streamlined
configuration
Primarily closed-source
Open Source Yes
open-source component
Limited support for ol
Microsoft Support Fully supported by Microsoft
versions
Modern web apps, cloud Legacy applications,
Suitable for
deployments, microservices specific deployments
What are the Thread and Process?
Process – Process is something that the operating system uses to execute a program
by providing the resources required. Each process has a unique process id associated
with it. We can view the process within which a program is running using the windows
task manager.
Thread – A Thread is a lightweight process that is responsible for executing application
code. A process has at least one thread which is commonly called the main thread which
actually executes the application code. A single process can have multiple threads.
Every application by default contains one thread to execute the program and that thread
is known as the main thread. So every program by default is a single-threaded model.
What is the difference between Process and Thread?
This is one of the most frequently asked Multithreading Interview Questions in C#. A
process is started when you start an Application. The process is a collection of
resources like virtual address space, code, security contexts, etc. A process can start
multiple threads. Every process starts with a single thread called the primary thread. You
can create n number of threads in a process. Threads share the resources allocated to
the process. A process is the parent and threads are his children.
Why we need Multi-threading in our project?
This is one of the most frequently asked Multithreading Interview Questions in C#.NET.
Let us discuss this question. Multi-threading is used to run multiple threads
simultaneously. Some main advantages are:
1. You can do multiple tasks simultaneously. For e.g. saving the details of the user
to a file while at the same time retrieving something from a web service.
2. Threads are much lightweight than process. They don’t get their own resources.
They used the resources allocated to a process.
3. Context-switch between threads takes less time than process.
What are the advantages and disadvantages of multithreading?
I think this MultiThreading Interview Question is the most asked interview question in the
dot net. So let us discuss the advantages and disadvantages
Advantages of multithreading:
1. To maintain a responsive user interface
2. It makes efficient use of processor time while waiting for I/O operations to
complete.
3. To split large, CPU-bound tasks to be processed simultaneously on a machine
that has multiple CPUs/cores.
Disadvantages of multithreading:
1. On a single-core/processor machine threading can affect performance negatively
as there is overhead involved with context-switching.
2. Have to write more lines of code to accomplish the same task.
3. Multithreaded applications are difficult to write, understand, debug, and maintain.
Please Note: Only use multithreading when the advantages of doing so outweigh the
disadvantages.
What is the difference between IEnumerable and IQueryable
in C#?
CsharpServer Side ProgrammingProgramming
IEnumerable exists in System.Collections Namespace.
IQueryable exists in System. Linq Namespace.
Both IEnumerable and IQueryable are forward collection.
IEnumerable doesn’t support lazy loading
IQueryable support lazy loading
Querying data from a database, IEnumerable execute a select query on the
server side, load data in-memory on a client-side and then filter data.
Querying data from a database, IQueryable execute the select query on the
server side with all filters.
IEnumerable Extension methods take functional objects.
IQueryable Extension methods take expression objects means expression tree.
Security in MVC
1. Cross Site Scripting (XSS).
2. Cross site request forgery (CSRF).
3. Authentication.
a. Windows
b. Forms
Cross Site Scripting (XSS)
XSS is a kind of attack, wherein any malicious user tries to inject scripts in input
fields like a TextBox or a textarea. This attack can affect my site by executing some
unwanted scripts. So we need to take care and avoid this kind of script injection. This
attack is most common, so Microsoft had a built-in functionality of handling these
scripts in HTML input tags.
Let’s consider a sample wherein I will use 2 TextBoxes and try inputting some script
tags as data.
Once I click on Ok, the SaveData Actionmethod will be triggered. This method
returns an aspx view.
1. public ActionResult Savedata(Customer c)
2. {
3. //Save logic
4. return View("SavedataAspx",c);
5. }
When I tried inputting this <b> tag, I got the following error. That says someone is
trying to insert the dangerous script. This threat is handled easily by the .Net
Framework.
But think of a case where I want to enter this kind of information in my TextBox like
styling the data. The best example is C-SharpCorner.com or CodeProject.com. I
mean I want to allow this script tag to be entered but as a data and not as an
executable code.
In this case I need to say, don’t validate these tags and print it after encoding. This
can be done by setting the attribute for ActionMethod.
1. [ValidateInput(false)]
2. public ActionResult Savedata(Customer c)
3. {
4. return View("SavedataAspx",c);
5. }
Note: This setting can be done at the global level also, in other words at webconfig.
1. <httpRuntime requestValidationMode="2.0"/>
After setting this attribute, I don’t get an error, instead it tries to execute the script or
render the tags entered into TextBox. This is true only if my view is .aspx.
Output:
To print the text as it is, then I need to use the Server.HtmlEncode() method as in
the following:
1. <%=Server.HtmlEncode(Model.CustomerAddr) %>
Output:
But if we return a Razor View Engine then this is automatically encoded by Html
helper methods for the input type.
Output:
Note: This signifies that when we use Razor syntax (Razor Engine), Cross Site
Scripting attack is prevented as it encodes the data as a default behavior. But with
Aspx engine, Cross Site Scripting is possible as a default behavior.
In case you want to execute the script in Razor then you can use
@Html.Raw(Model.CustomerAddr).
Cross Site Request Forgery (CSRF) Attack
Now the second important threat in the web application is a Cros
s Site Request Forgery (CSRF) Attack.
CSRF attack
This is the most common attack we find today. You may have seen an ad that
appears suddenly on some of the websites. Once we click on that popup ad, it
redirects to some URL and moves back to our own website. We think that it is just an
ad popup. But you have a wrong impression. Actually these redirects try to hack our
data or insert some invalid data in our website. This is what we call Cross Site
Request Forgery where we are redirect to other websites without our knowledge and
hacked our data.
I will like to show you a small demo of how forgery occurs.
1. Run the current application http://localhost:44247/Home/Index.
2. Right-click on the webpage and open view source.
It will look something like this.
3. Copy only the form tag section and paste it in a new HTML page. Note: This
HTML page is not needed to be in a same project. It can be an altogether
different application. Remove all the unwanted attributes and tags and keep
only the input type controls and the action should be the full
URL : http://localhost:44247/Home/SaveData as shown below:
1. <form action=" http://localhost:44247/Home/
SaveData" method="post" style=”display:none;”><
input name="CustomerId" type="text" value="1000
" /> <br />
2. <input id="CustomerName" name="CustomerName
" type="text" value="HACK" /> <br />
3. <textarea cols="20" id="CustomerAddr" name=
"CustomerAddr" rows="2">
4. HACK
5. </textarea>
6. </form>
Add a small JavaScript code :
7. <script type="text/javascript">
8. function fnCall() {
9. window.setTimeout(function(){ window.documen
t.getElementById("btnok").click();
10. }, 2000);
11. }
12. window.onload = fnCall();
13. </script>
4. Now set your own random text in a TextBox. Just to hide the form from others
set the style to display:none. and keeping the text as loading... Save the
HTML file with any name like Ad.html.
5. Run the HTML page.
Now since we have specified the post method to our original website, it will
redirect to our website and will execute the SaveData actionmethod. We will
get the output as:
Now I was able to access your website and post some malicious data. Think
of the situation where you have been saving the logic written in this
actionmethod and it contains one field that accepts an Amount. This is called
a Cross Site Request Forgery Attack.
This attack can be avoided in MVC using a token called AntiForgeryToken.
When posting the data to the server, keep a token key along with data that will
always validate on the server. This is done in MVC following 2 simple steps.
1. Add a Htmlhelper method @Html.AntiForgeryToken() within the form
tag. This will generate a Token key on the View.
2. Add an Attribute ValidateAntiForgeryToken on the Savedata
ActionMethod. This will validate the key passed in the post.
1. [ValidateInput(false)]
2. [ValidateAntiForgeryToken]
3. public ActionResult Savedata(Customer c)
4. {
5. // return View("SavedataAspx",c);
6. return View("Savedata", c);
7. }
That’s it. See the following code, how the token key looks as in.
Now if we try to run the same html file in other words- Ad.html, then we
will get an error:
I hope you got it.
Authentication
The third thing that we normally require in our website is Authentication.
Authentication in MVC is similar to ASP.Net Authentication but the syntax differs. In
Authentication, there are various ways, let’s talk about each one of them. For
showcasing Authentication, I am not using already available classes that come in
selecting the project template. I am manually creating the procedure.
a. Windows Authentication
This mainly is used for Intranet applications.
The following is the procedure to enable Windows authentication:
1. Go to the webconfig file, set the authentication tag with the mode set to
Windows.
1. <system.web>
2. <authentication mode="Windows"></
authentication>
3. </system.web>
2. By default, Windows Authentication is set to Disabled. Go to the
properties of the project and enable Windows Authentication.
3. This will enable your Windows authentication, so when you try to
access any ActionMethod from URL, you will be shown a credentials
window as shown below:
Enter your Windows credentials and everything works for you.
b. Forms Authentication
Now let’s talk about Forms Authentication. This is mainly used for Internet
applications. Use the following procedure:
1. Set the authentication mode in webconfig. Also set the default login
URL. This URL will be your controller/ActionMethod name.
1. <system.web>
2. <authentication mode="Forms">
3. <forms loginUrl="Account/Index" time
out="2000"></forms>
4. </authentication>
5. </system.web>
2. Create a model class LoginDetail.
1. public class LoginDetail
2. {
3. Required]
4. public string UserName { get; set; }
5.
6. [Required]
7. public string Password { get; set; }
8. }
3. Create a controller AccountController and add an actionmethod Index
and View to show the login screen of the strong type LoginDetail.
Add the attribute [AllowAnonymous] to the controller class (can be
added at actionmethod level also). This is required to exclude these
views from being authenticated. Find the code snippet below:
1. namespace SecurityProj.Controllers
2. {
3. [AllowAnonymous]
4. public class AccountController : Contr
oller
5. {
6.
7.
8. public ActionResult Index()
9. {
10. return View();
11. }
12.
13. public ActionResult Login(Log
inDetail user)
14. {
15. if (user.UserName == "pra
deep" && user.Password == "123")
16. {
17. System.Web.Security.F
ormsAuthentication.SetAuthCookie(user.User
Name, false);
18. return RedirectToActi
on("Index", "Home");
19. }
20. return View("Index");
21.
22. }
23.
24. }
25. }
In the preceding code if you see a Login action method, I have checked
for specific login name and password just for demo purpose and set
the Authentication cookie. Why do I need to set this cookie?
Once this cookie is set, the request will be considered authenticated.
System.Web.Security.FormsAuthentication.SetAuthCookie(user.UserN
ame, false);
The first parameter for this method is the value stored in a cookie
whereas the second value is to set whether the cookie should be
persistent or not.
Once authenticated, I am redirecting to Home/Index view.
4. Set the [Authorize] attribute just to the action methods that needs to go
through Authentication.
5. Execute the project and go to Home/Index. You will observe you are
redirected to Account/Login. This is because you have decorated the
Action Method or Home controller to [Authorize]. So it tries to
authenticate it. Once properly authenticated from the Login/Index view,
you are allowed to browse the website.
Note: Whichever actionmethod that you don’t want to be under
Authentication process can be specifeid by adding it with the Attribute
[AllowAnonymous].
If you check the cookie that is created on
calling FormsAuthentication.SetAuthCookie
The method is named .ASPXAUTH as in the following:
I hope you got it. In the same way on the click of logoff you can
delete that cookie.
If you observe, I need to provide an Authorize attribute at the controller
level. But I don’t want to do that because my entire website needs to be
authenticated and to write my custom logic. For that I can create my
own custom filter class inherited from the AuthorizeAttribute class as
shown below.
1. public class MyCustomAuth : AuthorizeAttri
bute
2. {
3. public override void OnAuthorization(Au
thorizationContext filterContext)
4. {
5. //Check over here
6. base.OnAuthorization(filterContext);
7. }
8. }
Register this class in Global.asax.
That’s it. Now your authentication will get executed throughout for all
the ActionMethod requests.
Conclusion
This completes the article on security in MVC. For authentication, if you select the
Internet or Intranet template when creating the new project, then you will get the
automated generated classes of model, view, action method already available. But
my intention was to show how internally it works. I hope you liked it. Please share
your thought or comments, whether good or bad. Sharing is valuable no matter what.
Sample code project is available for download.
Testing in MVC
(1) MS Test (in build inside dotnet project)
(2) NUnit-Test
(3) Moq
(4) X-unit – core
Difference between Ref and Out keywords
ref keyword out keyword
It is necessary the parameters should initialize It is not necessary to initialize
before it pass to ref. parameters before it pass to out.
It is necessary to initialize the value of a
It is not necessary to initialize the value of a parameter before returning to the callin
parameter before returning to the calling method. method.
The passing of value through ref parameter is The declaring of parameter through out
useful when the called method also need to parameter is useful when a method
change the value of passed parameter. return multiple values.
When ref keyword is used the data may pass in When out keyword is used the data only
bi-directional. passed in unidirectional.
Note: Both ref and out parameter treated same at compile-time but different
at run-time.
A SQL trigger is a database object which fires when an event occurs in a database.
We can execute a SQL query that will "do something" in a database when a change
occurs on a database table such as a record is inserted or updated or deleted. For
example, a trigger can be set on a record insert in a database table. For example, if
you want to increase the count of blogs in the Reports table when a new record is
inserted in the Blogs table, we can create a trigger on the Blogs' table on INSERT
and update the Reports table by increasing blog count to 1.
Types of Triggers
There are two types of triggers:
1. DDL Trigger
2. DML Trigger
DDL Triggers
The DDL triggers are fired in response to DDL (Data Definition Language) command
events that start with Create, Alter and Drop, such as Create_table, Create_view,
drop_table, Drop_view and Alter_table.
Code of a DDL Trigger
create trigger saftey
on database
for
create_table,alter_table,drop_table
as
print'you can not create ,drop and alter table in this
database'
rollback;
SQL
Copy
When we create, alter or drop any table in a database then the following message
appears:
DML Triggers
The DML triggers are fired in response to DML (Data Manipulation Language)
command events that start with Insert, Update, and Delete. Like insert_table,
Update_view and Delete_table.
create trigger deep
on emp
for
insert,update,delete
as
print'you can not insert,update and delete this table i'
rollback;
SQL
Copy
When we insert, update or delete in a table in a database then the following
message appears,
There are two types of DML triggers
AFTER Triggers
AFTER triggers are executed after the action of an INSERT, UPDATE, or DELETE
statement.
create trigger insertt
on emp
after insert
as
begin
insert into empstatus values('active')
end
SQL
Copy
INSTEAD Of Triggers
It will tell the database engine to execute the trigger instead of executing the
statement. For example an insert trigger executes when an event occurs instead of
the statement that would insert the values in the table .
CREATE TRIGGER instoftr
ON v11
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO emp
SELECT I.id, I.names
FROM INSERTED I
INSERT INTO emp1values
SELECT I.id1, I.name1
FROM INSERTED I
END
SQL
Copy
When we insert data into a view by the following query then it inserts values in both
tables :
insert into v11 values(1,'d','dd')
SQL
Copy
You can see both tables by the folowing query:
select * from emp
select * from emp1values
SQL
Copy
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view
are fields from one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as
if the data were coming from one single table.
A view is created with the CREATE VIEW statement.
CREATE VIEW Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Note: A view always shows up-to-date data! The database engine recreates
the view, every time a user queries it.
SQL CREATE VIEW Examples
The following SQL creates a view that shows all customers from Brazil:
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
Try it Yourself »
We can query the view above as follows:
Example
SELECT * FROM [Brazil Customers];
Try it Yourself »
The following SQL creates a view that selects every product in the "Products"
table with a price higher than the average price:
Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
Try it Yourself »
We can query the view above as follows:
Example
SELECT * FROM [Products Above Average Price];
Try it Yourself »
SQL Updating a View
A view can be updated with the CREATE OR REPLACE VIEW statement.
SQL CREATE OR REPLACE VIEW Syntax
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
Try it Yourself »
SQL Dropping a View
A view is deleted with the DROP VIEW statement.
SQL DROP VIEW Syntax
DROP VIEW view_name;
The following SQL drops the "Brazil Customers" view:
Example
DROP VIEW [Brazil Customers];
Try it Yourself »
Updating a View
A view can be updated under certain conditions which are given below −
The SELECT clause may not contain the keyword DISTINCT.
The SELECT clause may not contain summary functions.
The SELECT clause may not contain set functions.
The SELECT clause may not contain set operators.
The SELECT clause may not contain an ORDER BY clause.
The FROM clause may not contain multiple tables.
The WHERE clause may not contain subqueries.
The query may not contain GROUP BY or HAVING.
Calculated columns may not be updated.
All NOT NULL columns from the base table must be included in the view in
order for the INSERT query to function.
38. What are the types of views in SQL?
In SQL, the views are classified into four types. They are:
1. Simple View: A view that is based on a single table and does not
have a GROUP BY clause or other features.
2. Complex View: A complex view is one that is built from several
tables and includes a GROUP BY clause as well as functions.
3. Inline View: A view that is built on a subquery in the FROM Clause,
which provides a temporary table and simplifies a complicated query.
4. Materialized View: A view that saves both the definition and the
details. It builds data replicas by physically preserving them.
SQL Server Views Interview Questions
Back to: Dot Net Interview Questions and Answers
SQL Server Views Interview Questions and Answers
In this article, I am going to discuss the most frequently asked SQL Server Views
Interview Questions and Answers. Please read our previous article where we
discussed the most frequently asked SQL Server Triggers Interview Questions with
Answers. As part of this article, we are going to discuss the following SQL Server Views
Interview Questions with answers.
1. What is a View in SQL Server?
2. What are the differences between a table and a view in SQL Server?
3. How many types of views are there in SQL Server?
4. What is a simple view or Updatable view?
5. What is a complex View in SQL Server?
6. Can we drop a table that has dependent views on it?
7. Can we create a view based on other views?
8. Can we update the views in SQL Server?
9. Why do we need Views in SQL Server?
10. What are the advantages of using views? OR when do you usually use
views?
11. What are indexed views? Or What are materialized views?
12. What are the limitations of a View in SQL Server?
What is a View in SQL Server?
A view is nothing more than a saved SQL query. A view can also be considered as a
virtual table. So, we can think of a view either as a compiled SQL query or a virtual table.
As a view represents a virtual table it does not physically store any data by default.
When we query a view we actually, retrieve the data from the underlying database
tables.
What are the differences between a table and a view?
When compared with a table we have the following differences between a table and
view.
1. The table is physical and the view is logical
2. A table is an independent object whereas view is a dependent object that is a
view depends on a table or tables from which it is loading the data.
3. When a new table is created from an existing table the new and old tables are
independent themselves that is the changes of one table will not be reflected into
the other table whereas if a view is created based on a table any changes that
are performed on the table reflects into the view and any changes performed on
the view reflected in the table also.
How many types of views are there in SQL Server?
We can create the view in two ways those are
1. Simple view and Updatable views
2. Complex view and non-updatable views.
What is a simple view or Updatable view?
1. The view which is created basing on the columns of a single table is known as
the simple view.
2. We can perform all DML operations on a simple view so that a simple view is also
called an updatable view or dynamic view.
What is a complex View in SQL Server?
1. When we create a view on more than 1 table then it is known as the complex
view.
2. On a complex view, we cannot perform DML operations so that a complex view is
also called a non-updatable or static view.
Can we drop a table that has dependent views on it?
Yes, we can drop a table even if any dependent views are associated with it, but the
views that are associated with it will not be dropped. They will still execute in the
database only with the status as inactive object and all those views become active and
start functioning provided the table is recreated.
Can we create a view based on other views?
Yes, we can create a view based on other views. Usually, we create views based on
tables, but it is also possible to create views based on views.
Can we update the views?
Yes, views can be updated. However, updating a view that is based on multiple tables,
may not update the underlying tables correctly. To correctly update a view that is based
on multiple tables we can make use “Instead OF triggers” in SQL Server.
Why do we need Views in SQL Server?
To protect the data. If we have a table containing sensitive data in certain columns, we
might wish to hide those columns from certain groups of users. For instance, customer
names, addresses, and social security numbers might all be stored in the same table;
however, for lower-level employees like shipping clerks, you can create a view that only
displays customer name and address. You can grant permissions to a view without
allowing users to query the original tables.
A view is a logical table but what it stores internally is a select statement that is used for
creating the view. So that whenever a user performs an operation on the view like select,
insert, update or delete internally the view performs those operations on a table.
Simply we can say that view will act as an interface between the data provider (Table)
and the User.
A view is created based on a table any changes that are performed on the table reflect
into the view any changes performed on the view reflected in the table also.
What are the advantages of using views? OR when do you usually use
views?
Advantages of using views:
Views can be used to reduce the complexity of the database schema, for non-IT
users. The sample view, vWEmployeesByDepartment, hides the complexity of joins.
Non-IT users find it easy to query the view, rather than writing complex joins.
Views can be used as a mechanism to implement row and column level security.
Row Level Security:
For example, I want an end-user, to have access only to IT Department employees. If I
grant him access to the underlying tblEmployees and tblDepartments tables, he will be
able to see, every department employee. To achieve this, I can create a view, which
returns only IT Department employees, and grants the user access to the view and not
to the underlying table.
Column Level Security:
Salary is confidential information and I want to prevent access to that column. To
achieve this, we can create a view, which excludes the Salary column, and then grant
the end-user access to these views rather than the base tables.
Views can be used to present only aggregated data and hide detailed data. The view
that returns summarized data, Total number of employees by Department.
What are indexed views? Or What are materialized views?
A view is a virtual table that means it does not contain any physical data. A view is
nothing more than a compiled SQL query. Every time, we issue a select query against a
view, we actually get the data from the underlying base tables and not from the view, as
the view itself does not contain any data.
When we create an index on a view, the data gets physically stored in the view. So,
when we issue a select query against an indexed view, the data is retrieved from the
index without having to go to the underlying table, which will make the select statement
to work slightly faster. However, the disadvantage is INSERT, UPDATE and DELETE
operations will become a little slow, because every time we insert or delete a row from
the underlying table, the view index needs to be updated. In short, DML operations will
have a negative impact on performance.
Oracle refers to indexed views as materialized views.
Only the views created with schema binding can have an Index. Simply adding WITH
SCHEMABINDING to the end of the CREATE VIEW statement will accomplish this.
However, the effect is that any changes to the underlying tables which will impact the
view are not allowed. Since the indexed view is stored physically, any schema changes
would impact the schema of the stored results set. Therefore, SQL Server requires that
schema binding is used to prevent the view’s schema (and therefore the underlying
tables) from changing.
The first index for a view must be a UNIQUE CLUSTERED INDEX, after which, it’s
possible to create non-clustered indexes against the view.
Indexed Views are heavily used in data warehouses and reporting databases that are
not highly transactional.
What are the limitations of a View?
1. We cannot pass parameters to a view.
2. Rules and Defaults cannot be associated with views.
3. The ORDER BY clause is invalid in views unless TOP or FOR XML is also
specified.
4. Views cannot be based on temporary tables.
Collections in C#
2 types of collections
(1) Non-generic (2) Generic
Stack -------------> Stack [push]
Queue -------------> Queue [enqueue]
ArrayList -------------> List [Add]
HashTable -------------> Dictionary [Add]
SortedList -------------> SortedList [Add]
https://www.codeproject.com/Tips/1157683/Csharp-Inheritance-Interview-Point-of-View
How to use ajax request in mvc
@using (Ajax.BeginForm("EmployeeMaster", "Home", new AjaxOptions { H
ttpMethod = "POST", UpdateTargetId = "divEmp" }))
How to use IN clause in Linq
This will translate to a where in clause in Linq to SQL...
var myInClause = new string[] {"One", "Two", "Three"};
var results = from x in MyTable
where myInClause.Contains(x.SomeColumn)
select x;
// OR
var results = MyTable.Where(x => myInClause.Contains(x.SomeColumn));
Difference between readonly and const keyword in C#
CsharpServer Side ProgrammingProgramming
readonly keyword
readonly keyword is used to define a variable which can be assigned once after
declaration either during declaration or in constructor. const keyword is used to
define a constant to be used in the program. Following is the valid usage of a
readonly and const keywords in C#.
Example
Live Demo
using System.IO;
using System;
public class Program {
public const int VALUE = 10;
public readonly int value1;
Program(int value){
value1 = value;
}
public static void Main() {
Console.WriteLine(VALUE);
Program p1 = new Program(11);
Console.WriteLine(p1.value1);
}
}
Output
10
11
Following are some of the important differences between readonly and const
keywords.
Sr. Key readonly keyword const keyword
No.
Purpose readonly keyword is used to create a readonly const keyword is used to create
1
fields. constant fields.
Type readonly is a constant defined at runtime. const is used to create a constan
2
at compile time.
Change readonly field value can be changed after const field value cannot be
3
declaration. changed after declaration.
Method readonly fields cannot be defined within a const fields can be declared
4
method. within a method.
5 Value readonly variables are declared as instance const fields are to be assigned a
Sr. Key readonly keyword const keyword
No.
assignment variable and assigned values in constructor. the time of declaration.
ReadOnly Vs Const Keyword
ReadOnly Keyword Const Keyword
In C#, readonly fields can be created using In C#, constant fields are created
readonly keyword using const keyword.
ReadOnly is a runtime constant. Const is a compile time constant.
The value of the const field can not
The value of readonly field can be changed. be changed.
It can be declared inside the
It cannot be declared inside the method. method.
In readonly fields, we can assign values in In const fields, we can only assign
declaration and in the constructor part. values in declaration part.
It cannot be used with static
It can be used with static modifiers. modifiers.
WCF :
(A) InstanceContextMode :- [On Service class , ServiceBehaviour]
(1) Per Call
(2) Per Session (Default)
(3) Single
(B) Concurrency Mode : [On Service class , ServiceBehaviour]
(1) Single (Default)
(2) Multiple
(3) Reentrant
(B) Messaging Pattern :- [On OperationContract]
(1) Request - Reply (Default)
(2) Duplex
(3) One Way
(C) Session Mode :- [On ServiceContract]
(1) Allowed (Default)
(2) NotAllowed
(3) Required
How do we implement Abstraction in c# ?
In C# abstraction is achieved with the help of Abstract classes. An abstract class is
declared with the help of abstract keyword. In C#, you are not allowed to create objects of
the abstract class. Or in other words, you cannot use the abstract class directly with the new
operator.
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract classes or interfaces
The abstract keyword is used for classes and methods:
Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does
not have a body. The body is provided by the derived class (inherited
from).
Why And When To Use Abstract Classes and Methods?
To achieve security - hide certain details and only show the important details
of an object.
Note: Abstraction can also be achieved with Interfaces
Another way to achieve abstraction in C#, is with interfaces.
An interface is a completely "abstract class", which can only contain
abstract methods and properties (with empty bodies):
By default, members of an interface are abstract and public.
Note: Interfaces can contain properties and methods, but not fields.
Why And When To Use Interfaces?
1) To achieve security - hide certain details and only show the important
details of an object (interface).
2) C# does not support "multiple inheritance" (a class can only inherit from
one base class). However, it can be achieved with interfaces, because the
class can implement multiple interfaces. Note: To implement multiple
interfaces, separate them with a comma (see example below).
How do we implement Encapsulation in c# ?
As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding. Encapsulation can be achieved by: Declaring all the
variables in the class as private and using C# Properties in the class to set and
get the values of variables.
How do we implement Polymorphism in c# ?
2 types of polymorphism are present :
(1) Compile time/ Early binding Polymorphism is implemented by using Method
overloading
Example : We can give backward compatibility to user, when we have method with 2
parameter and we do not want to disturb existing clients and implement same method with
3 parameters, we create method with same name and 3 parameters and let other client to
use this method
(2) Run time Polymorphism/ Late Binding/ Dynamic Binding is implemented by
[Method Overriding] using virtual and override methods with same names in
parent and child classes. And type of class object use to call the method that
method will be called from child or parent class. It is called runtime
polymorphism because which method to call from parent or child is decided
at runtime with the type of class object used to call the method
Example :
JWT in ASP.NET Core
JWT (JSON web token) has become more and more popular in web development.
It is an open standard which allows transmitting data between parties as a JSON
object in a secure and compact way. The data transmitting using JWT between
parties are digitally signed so that it can be easily verified and trusted.
The first step is to configure JWT based authentication in our project. To do this,
we need to register a JWT authentication schema by using "AddAuthentication"
method and specifying JwtBearerDefaults.AuthenticationScheme. Here, we
configure the authentication schema with JWT bearer options.
1. public void ConfigureServices(IServiceCollection serv
ices)
2. {
3. services.AddAuthentication(JwtBearerDefaults.Auth
enticationScheme)
4. .AddJwtBearer(options =>
5. {
6. options.TokenValidationParameters = new TokenValid
ationParameters
7. {
8. ValidateIssuer = true,
9. ValidateAudience = true,
10. ValidateLifetime = true,
11. ValidateIssuerSigningKey = true,
12. ValidIssuer = Configuration["Jwt:Issuer"],
13. ValidAudience = Configuration["Jwt:Issue
r"],
14. IssuerSigningKey = new SymmetricSecurityKey(E
ncoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
15. };
16. });
17. services.AddMvc();
18. }
In this example, we have specified which parameters must be taken into account
to consider JWT as valid. As per our code, the following items consider a token
valid:
Validate the server (ValidateIssuer = true) that generates the token.
Validate the recipient of the token is authorized to receive
(ValidateAudience = true)
Check if the token is not expired and the signing key of the issuer is
valid (ValidateLifetime = true)
Validate signature of the token (ValidateIssuerSigningKey = true)
Additionally, we specify the values for the issuer, audience, signing
key. In this example, I have stored these values in appsettings.json
file.
AppSetting.Json
1. {
2. "Jwt": {
3. "Key": "ThisismySecretKey",
4. "Issuer": "Test.com"
5. }
6. }
The above-mentioned steps are used to configure a JWT based authentication
service. The next step is to make the authentication service is available to the
application. To do this, we need to call app.UseAuthentication() method in the
Configure method of startup class. The UseAuthentication method is called
before UseMvc method.
1. public void Configure(IApplicationBuilder app, IHosti
ngEnvironment env)
2. {
3. app.UseAuthentication();
4. app.UseMvc();
5. }
Generate JSON Web Token
I have created a LoginController and Login method within this controller, which is
responsible to generate the JWT. I have marked this method with the
AllowAnonymous attribute to bypass the authentication. This method expects the
Usermodel object for Username and Password.
I have created the "AuthenticateUser" method, which is responsible to validate
the user credential and returns to the UserModel. For demo purposes, I have
returned the hardcode model if the username is "Jignesh". If the
"AuthenticateUser" method returns the user model, API generates the new token
by using the "GenerateJSONWebToken" method.
Here, I have created a JWT using the JwtSecurityToken class. I have created
an object of this class by passing some parameters to the constructor such as
issuer, audience, expiration, and signature.
Finally, JwtSecurityTokenHandler.WriteToken method is used to generate the
JWT. This method expects an object of the JwtSecurityToken class.
1. using Microsoft.AspNetCore.Authorization;
2. using Microsoft.AspNetCore.Mvc;
3. using Microsoft.Extensions.Configuration;
4. using Microsoft.IdentityModel.Tokens;
5. using System;
6. using System.IdentityModel.Tokens.Jwt;
7. using System.Security.Claims;
8. using System.Text;
9.
10. namespace JWTAuthentication.Controllers
11. {
12. [Route("api/[controller]")]
13. [ApiController]
14. public class LoginController : Controller
15. {
16. private IConfiguration _config;
17.
18. public LoginController(IConfiguration config)
19. {
20. _config = config;
21. }
22. [AllowAnonymous]
23. [HttpPost]
24. public IActionResult Login([FromBody]UserModel lo
gin)
25. {
26. IActionResult response = Unauthorized();
27. var user = AuthenticateUser(login);
28.
29. if (user != null)
30. {
31. var tokenString = GenerateJSONWebTok
en(user);
32. response = Ok(new { token = tokenString }
);
33. }
34.
35. return response;
36. }
37.
38. private string GenerateJSONWebToken(UserModel use
rInfo)
39. {
40. var securityKey = new SymmetricSecurityKey(En
coding.UTF8.GetBytes(_config["Jwt:Key"]));
41. var credentials = new SigningCredentials
(securityKey, SecurityAlgorithms.HmacSha256);
42.
43. var token = new JwtSecurityToken(_config
["Jwt:Issuer"],
44. _config["Jwt:Issuer"],
45. null,
46. expires: DateTime.Now.AddMinutes(120),
47. signingCredentials: credentials);
48.
49. return new JwtSecurityTokenHandler().Wri
teToken(token);
50. }
51.
52. private UserModel AuthenticateUser(UserModel logi
n)
53. {
54. UserModel user = null;
55.
56. //Validate the User Credentials
57. //Demo Purpose, I have Passed HardCoded
User Information
58. if (login.Username == "Jignesh")
59. {
60. user = new UserModel { Username = "Jignes
h Trivedi", EmailAddress = "[email protected]" };
61. }
62. return user;
63. }
64. }
65. }
Once, we have enabled the JWT based authentication, I have created a simple
Web API method that returns a list of value strings when invoked with an HTTP
GET request. Here, I have marked this method with the authorize attribute, so
that this endpoint will trigger the validation check of the token passed with an
HTTP request.
If we call this method without a token, we will get 401 (UnAuthorizedAccess)
HTTP status code as a response. If we want to bypass the authentication for any
method, we can mark that method with the AllowAnonymous attribute.
To test the created Web API, I am Using Fiddler. First, I have requested to
"API/login" method to generate the token. I have passed the following JSON in
the request body.
1. {"username": "Jignesh", "password": "password"}
As a response, we will get the JSON like the following,
1. {
2. "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdW
IiOiJKaWduZXNoIFRyaXZlZGkiLCJlbWFpbCI6InRlc3QuYnRlc3RAZ21h
aWwuY29tIiwiRGF0ZU9mSm9pbmciOiIwMDAxLTAxLTAxIiwianRpIjoiYz
JkNTZjNzQtZTc3Yy00ZmUxLTgyYzAtMzlhYjhmNzFmYzUzIiwiZXhwIjox
NTMyMzU2NjY5LCJpc3MiOiJUZXN0LmNvbSIsImF1ZCI6IlRlc3QuY29tIn
0.8hwQ3H9V8mdNYrFZSjbCpWSyR1CNyDYHcGf6GqqCGnY"
3. }
Now, we will try to get the list of values by passing this token into the
authentication HTTP header. Following is my Action method definition.
1. [HttpGet]
2. [Authorize]
3. public ActionResult<IEnumerable<string>> Get()
4. {
5. return new string[] { "value1", "value2", "value3
", "value4", "value5" };
6. }
1. Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp
XVCJ9.eyJzdWIiOiJKaWduZXNoIFRyaXZlZGkiLCJlbWFpbCI6InR
lc3QuYnRlc3RAZ21haWwuY29tIiwiRGF0ZU9mSm9pbmciOiIwMDAx
LTAxLTAxIiwianRpIjoiYzJkNTZjNzQtZTc3Yy00ZmUxLTgyYzAtM
zlhYjhmNzFmYzUzIiwiZXhwIjoxNTMyMzU2NjY5LCJpc3MiOiJUZX
N0LmNvbSIsImF1ZCI6IlRlc3QuY29tIn0.8hwQ3H9V8mdNYrFZSjb
CpWSyR1CNyDYHcGf6GqqCGnY
4. What is the difference between Web API and WCF?
WCF (Windows Communication Foundation): It is a framework used for
developing SOAP (Service-oriented applications). This framework is used
for developing, configuring, and deploying, or implementing network-
distributed services.
Web API: It is an application programming interface for both web
browsers and web servers. Browser API simply extends or increases the
functionality of web browsers whereas Server API simply extends or
increases the functionality of web server.
Web API WCF
It is used to develop both SOAP-based It is used to deploy only SOAP-based
services and RESTful services. services.
It supports various MVC features such as
It does not support any MVC features.
routing, model binding, etc.
It supports various protocols such as
It only supports HTTP protocol.
HTTP, UDP, custom transport.
It is considered best for developing It supports only limited RESTFUL
RESTFUL services. services.
It is good when one wants to expose an
It is good for creating services that
expensive range of clients such as
uses expedite transport channels such
iPhones, browsers, mobile phones, tablets,
as TCP, UDP, Named pipes, etc.
etc.
It offers TEXT, Binary encoding
It offers support for UTF-8 encoding
support, MTOM (Message Transmission
format.
Optimization Mechanism), etc.
5. Why to choose Web API over WCF?
Web API is considered the best choice over WCF because of the following
reasons:
Web API uses all features of HTTP such as URIs, request/response headers,
caching, versioning, various content formats, etc.
One does not have to define or explain any extra config setting for
different devices in Web API.
Web API uses different text formats including XML because of which it is
faster and more preferred for lightweight services.
Web API also supports MVC features whereas WCF does not support MVC
features.
Web API provides more flexibility as compared to WCF.
Web API uses standard security like token authentication, basic
authentication, etc., to provide secure service whereas WCF uses WS-I
standard to provide secure service.
Static constructor does not have parameters
Difference between CTE and Temp
Table and Table Variable
In SQL Server, we have various options for storing data temporarily.
Temp Table, Table variable and CTE are commonly used way for
storing temporary data. In this article, you will learn about the main
differences between Temp Table, Table variable and CTE.
CTE - Common Table Expressions
CTE stands for Common Table Expressions. It was introduced with
SQL Server 2005. It is a temporary result set and typically it may be
a result of complex sub-query. Unlike the temporary table, its life is
limited to the current query. It is defined by using WITH statement.
CTE improves readability and ease in maintenance of complex
queries and sub-queries. Always begin CTE with a semicolon.
A subquery without CTE is given below :
SELECT * FROM (
SELECT Addr.Address, Emp.Name, Emp.Age From Address Addr
Inner join Employee Emp on Emp.EID = Addr.EID) Temp
WHERE Temp.Age > 50
ORDER BY Temp.NAME
By using CTE above query can be re-written as follows :
;With CTE1(Address, Name, Age)--Column names for CTE, which are optional
AS
SELECT Addr.Address, Emp.Name, Emp.Age from Address Addr
INNER JOIN EMP Emp ON Emp.EID = Addr.EID
SELECT * FROM CTE1 --Using CTE
WHERE CTE1.Age > 50
ORDER BY CTE1.NAME
When to use CTE?
1. This is used to store the result of a complex subquery for further
use.
2. This is also used to create a recursive query.
Temporary Tables
In SQL Server, temporary tables are created at run-time and you can
do all the operations which you can do on a normal table. These
tables are created inside the Tempdb database. Based on the scope
and behavior temporary tables are of two types as given below-
1. Local Temp Table
Local temp tables are only available to the SQL Server session
or connection (means single user) that created the tables. These
are automatically deleted when the session that created the
tables has been closed. The local temporary table name is
stared with a single hash ("#") sign.
CREATE TABLE #LocalTemp
UserID int,
Name varchar(50),
Address varchar(150)
GO
insert into #LocalTemp values ( 1, 'Shailendra','Noida');
GO
Select * from #LocalTemp
The scope of Local temp table exists to the current session of
the current user means to the current query window. If you will
close the current query window or open a new query window
and will try to find above-created temp table, it will give you the
error.
2. Global Temp Table
Global temp tables are available to all SQL Server sessions or
connections (means all the user). These can be created by any
SQL Server connection user and these are automatically deleted
when all the SQL Server connections have been closed. The
global temporary table name is stared with double hash ("##")
sign.
CREATE TABLE ##GlobalTemp
UserID int,
Name varchar(50),
Address varchar(150)
GO
insert into ##GlobalTemp values ( 1, 'Shailendra','Noida');
GO
Select * from ##GlobalTemp
Global temporary tables are visible to all SQL Server
connections while Local temporary tables are visible to only
current SQL Server connection.
Table Variable
This acts like a variable and exists for a particular batch of query
execution. It gets dropped once it comes out of the batch. This is
also created in the tempdb database but not the memory. This also
allows you to create a primary key, identity at the time of Table
variable declaration but not non-clustered index.
GO
DECLARE @TProduct TABLE
SNo INT IDENTITY(1,1),
ProductID INT,
Qty INT
--Insert data to Table variable @Product
INSERT INTO @TProduct(ProductID,Qty)
SELECT DISTINCT ProductID, Qty FROM ProductsSales ORDER BY ProductID ASC
--Select data
Select * from @TProduct
--Next batch
GO
Select * from @TProduct --gives error in next batch
Note
1. Temp Tables are physically created in the tempdb database. These
tables act as the normal table and also can have constraints, an
index like normal tables.
2. CTE is a named temporary result set which is used to manipulate
the complex sub-queries data. This exists for the scope of a
statement. This is created in memory rather than the Tempdb
database. You cannot create an index on CTE.
3. Table Variable acts like a variable and exists for a particular batch of
query execution. It gets dropped once it comes out of a batch. This
is also created in the tempdb database but not the memory.
Why we need Tasks?
It can be used whenever you want to execute something in parallel.
Asynchronous implementation is easy in a task, using’ async’ and ‘await’
keywords.
Why we need a Thread?
When the time comes when the application is required to perform few
tasks at the same time.
Differences Between Task And Thread
Here are some differences between a task and a thread.
1. The Thread class is used for creating and manipulating a thread in Windows.
A Task represents some asynchronous operation and is part of the Task
Parallel Library, a set of APIs for running tasks asynchronously and in
parallel.
2. The task can return a result. There is no direct mechanism to return the
result from a thread.
3. Task supports cancellation through the use of cancellation tokens. But
Thread doesn't.
4. A task can have multiple processes happening at the same time. Threads
can only have one task running at a time.
5. We can easily implement Asynchronous using ’async’ and ‘await’ keywords.
6. A new Thread()is not dealing with Thread pool thread, whereas Task does
use thread pool thread.
7. A Task is a higher level concept than Thread.
(1) Why is Dotnet Core more useful than old dotnet Core ?
(2) What are the features of Dotnet Core ?
A) Dependency Injection
B) Open source
C) Modular with middleware components which help to make request and response
pipeline, Middleware concept is provided out of the box
D) Cross platform
(1) Can be run on multiple platforms like windows, mac , Linux
(2) Can be hosted on IIS, Apache, …..
E) Unified programming model for mvc and web api both r inherited from Controller class
F) Testing
(3) What is Asp.net Core ?
(A) Asp.net core is cross platform, high performance, open source framework for cloud based
and internet based applications
IIS, Nginx,
OUT OF PROCESS Apache
Internet Kestrel
HOSTING (Proxy
Server)
Process used : dotnet.exe
==================================================================================
IN PROCESS
HOSTING Internet IIS
Process used : w3wp.exe or iisexpress
What is repository pattern ?
A) Repository pattern is an abstraction of Data Access Layer. It hides the details of how data
is saved and retrieved from DB. The details of how data is saved and retrieved from DB is
in the respective repository
How to use Authorize to be used global in dotnet core ?
A) Startup => configureservices => services.AddMvc(policy = new
AuthorizationPolicyBuilder().RequireAuthentiicatedUser()) options.Filters.add(new
AuthorizationFilter(policy))
ASP. NET Core is an open-source an asp.net core training cross-
platform that runs on Windows, Linux, and Mac to develop modern
cloud-based applications including IoT apps, Web Apps, Mobile
Backends, and more. It is the fastest web development framework
from NodeJS, Java Servlet, PHP in raw performance, and Ruby on
Rails.
Learning pedagogy has evolved with the advent of technology over
the years. ASP.NET core training will help you to know about this
technology in a better way. Through the training session, you would
be able to know that ASP.NET core is not an upgraded version of
ASP.NET. ASP. NET Core is completely rewriting the work with
the .NET framework. It is much faster, modular, configurable,
scalable, cross-platform, and extensible support of .NET world for
which organizations from different parts of the world are grabbing
this technology in faster growth. Even it can work with both .NET
Core and .NET framework via the .NET standard framework.
Prepare yourself for the interview with the help of the ASP.NET
Core interview question answer Pdf file and get a suitable
development position on the cloud-based application including web
application, IoT application, and Mobile application.
More: ASP.NET Core Interview Questions and Answers PDF
Download
1. What is the ASP.NET Core?
ASP.NET Core is not an upgraded version of ASP.NET. ASP.NET Core
is completely rewriting that work with .net Core framework. It is
much faster, configurable, modular, scalable, extensible and cross-
platform support. It can work with both .NET Core and .net
framework via the .NET standard framework. It is best suitable for
developing cloud-based such as web application, mobile application,
IoT application.
2. What are the features provided by ASP.NET Core?
Following are the core features that are provided by the ASP.NET
Core
Built-in supports for Dependency Injection
Built-in supports for the logging framework and it can be
extensible
Introduced new, fast and cross-platform web server -
Kestrel. So, a web application can run without IIS, Apache,
and Nginx.
Multiple hosting ways are supported
It supports modularity, so the developer needs to include
the module required by the application. However, .NET
Core framework is also providing the meta package that
includes the libraries
Command-line supports to create, build and run the
application
There is no web.config file. We can store the custom
configuration into an appsettings.json file
There is no Global.asax file. We can now register and use
the services into startup class
It has good support for asynchronous programming
Support WebSocket and SignalR
Provide protection against CSRF (Cross-Site Request
Forgery)
3. What are the advantages of ASP.NET Core over
ASP.NET?
There are following advantages of ASP.NET Core over ASP.NET :
It is cross-platform, so it can be run on Windows, Linux,
and Mac.
There is no dependency on framework installation
because all the required dependencies are ship with our
application
ASP.NET Core can handle more request than the ASP.NET
Multiple deployment options available withASP.NET Core
4. What is Metapackages?
The framework .NET Core 2.0 introduced Metapackage that includes
all the supported package by ASP.NET code with their dependencies
into one package. It helps us to do fast development as we don't
require to include the individual ASP.NET Core packages. The
assembly Microsoft.AspNetCore.All is a meta package provide by
ASP.NET core.
5. Can ASP.NET Core application work with full .NET
4.x Framework?
Yes. ASP.NET core application works with full .NET framework via the
.NET standard library.
6. What is the startup class in ASP.NET core?
Startup class is the entry point of the ASP.NET Core application.
Every .NET Core application must have this class. This class contains
the application configuration rated items. It is not necessary that
class name must "Startup", it can be anything, we can configure
startup class in Program class.
public class Program
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<TestClass>();
What is the use of ConfigureServices method of
startup class?
This is an optional method of startup class. It can be used to
configure the services that are used by the application. This method
calls first when the application is requested for the first time. Using
this method, we can add the services to the DI container, so
services are available as a dependency in controller constructor.
7. What is the use of the Configure method of startup
class?
It defines how the application will respond to each HTTP request. We
can configure the request pipeline by configuring the middleware. It
accepts IApplicationBuilder as a parameter and also it has two
optional parameters: IHostingEnvironment and ILoggerFactory.
Using this method, we can configure built-in middleware such as
routing, authentication, session, etc. as well as third-party
middleware.
8. What is middleware?
It is a piece of software which is injected into the application
pipeline to handle request and responses. They are just like chained
to each other and form as a pipeline. The incoming requests are
passes through this pipeline where all middleware is configured, and
middleware can perform some action on the request before passes
it to the next middleware. Same as for the responses, they are also
passing through the middleware but in reverse order.
9. What is the difference between
IApplicationBuilder.Use() and
IApplicationBuilder.Run()?
We can use both the methods in Configure methods of startup class.
Both are used to add middleware delegate to the application
request pipeline. The middleware adds using IApplicationBuilder.Use
may call the next middleware in the pipeline whereas the
middleware adds using IApplicationBuilder.Run method never calls
the subsequent ore next middleware. After IApplicationBuilder.Run
method, system stop adding middleware in request pipeline.
10. What is the use of "Map" extension while
adding middleware to ASP.NET Core pipeline?
It is used for branching the pipeline. It branches the ASP.NET Core
pipeline based on request path matching. If request path starts with
the given path, middleware on to that branch will execute.
public void Configure(IApplicationBuilder app)
app.Map("/path1", Middleware1);
app.Map("/path2", Middleware2);
11. What is routing in ASP.NET Core?
Routing is functionality that map incoming request to the route
handler. The route can have values (extract them from URL) that
used to process the request. Using the route, routing can find route
handler based on URL. All the routes are registered when the
application is started. There are two types of routing supported by
ASP.NET Core
The conventional routing
Attribute routing
The Routing uses routes for map incoming request with route
handler and Generate URL that used in response. Mostly, the
application having a single collection of routes and this collection
are used for the process the request. The RouteAsync method is
used to map incoming request (that match the URL) with available
in route collection.
12. How to enable Session in ASP.NET Core?
The middleware for the session is provided by the package
Microsoft.AspNetCore.Session. To use the session in ASP.NET Core
application, we need to add this package to csproj file and add the
Session middleware to ASP.NET Core request pipeline.
public class Startup
public void ConfigureServices(IServiceCollection services)
….
….
services.AddSession();
services.AddMvc();
public void Configure(IApplicationBuilder app, IHostingEnvironment
env)
….
….
app.UseSession();
….
….
13. What are the various JSON files available in
ASP.NET Core?
There are following JSON files in ASP.NET Core :
global.json
launchsettings.json
appsettings.json
bundleconfig.json
bower.json
package.json
14. What is tag helper in ASP.NET Core?
It is a feature provided by Razor view engine that enables us to
write server-side code to create and render the HTML element in
view (Razor). The tag-helper is C# classes that used to generate the
view by adding the HTML element. The functionality of tag helper is
very similar to HTML helper of ASP.NET MVC.
Example:
//HTML Helper
@Html.TextBoxFor(model => model.FirstName, new { @class = "form-
control", placeholder = "Enter Your First Name" })
//content with tag helper
<input asp-for="FirstName" placeholder="Enter Your First Name"
class="form-control" />
//Equivalent HTML
<input placeholder="Enter Your First Name" class="form-control"
id="FirstName" name="FirstName" value="" type="text">
15. How to disable Tag Helper at element level?
We can disable Tag Helper at element level using the opt-out
character ("!"). This character must apply opening and closing the
Html tag.
Example
<!span asp-validation-for="phone" class="divPhone"></!span>
16. What are Razor Pages in ASP.NET Core?
This is a new feature introduced in ASP.NET Core 2.0. It follows a
page-centric development model just like ASP.NET web forms. It
supports all the feature of ASP.NET Core.
Example
@page
<h1> Hello, Book Reader!</h1>
<h2> This is Razor Pages </h2>
The Razor pages start with the @page directive. This directive
handle request directly without passing through the controller. The
Razor pages may have code behind file, but it is not really code-
behind file. It is class inherited from PageModel class.
17. How can we do automatic model binding in
Razor pages?
The Razor pages provide the option to bind property automatically
when posted the data using BindProperty attribute. By default, it
only binds the properties only with non-GET verbs. we need to set
SupportsGet property to true to bind a property on getting request.
Example
public class Test1Model : PageModel
[BindProperty]
public string Name { get; set; }
}
18. How can we inject the service dependency into
the controller?
There are three easy steps to add custom service as a dependency
on the controller.
Step 1: Create the service
public interface IHelloWorldService
string SaysHello();
public class HelloWorldService: IHelloWorldService
public string SaysHello()
return "Hello ";
Step 2: Add this service to Service container (service can either
added by singleton, transient or scoped)
public void ConfigureServices(IServiceCollection services)
….
services.AddTransient<IHelloWorldService, HelloWorldService>();
}
Step 3: Use this service as a dependency in the controller
public class HomeController: Controller
IHelloWorldService _helloWorldService;
public HomeController(IHelloWorldService helloWorldService)
_helloWorldService = helloWorldService;
19. How to specify service lifetime for register
service that added as a dependency?
ASP.NET Core allows us to specify the lifetime for registered
services. The service instance gets disposed of automatically based
on a specified lifetime. So, we do not care about the cleaning these
dependencies, it will take care by ASP.NET Core framework. There is
three type of lifetimes.
Singleton
ASP.NET Core will create and share a single instance of the service
through the application life. The service can be added as a singleton
using AddSingleton method of IServiceCollection. ASP.NET Core
creates service instance at the time of registration and subsequence
request use this service instance. Here, we do not require to
implement Singleton design pattern and single instance maintained
by the ASP.NET Core itself.
Example
services.AddSingleton<IHelloWorldService, HelloWorldService>();
Transient
ASP.NET Core will create and share an instance of the service every
time to the application when we ask for it. The service can be added
as Transient using AddTransient method of IServiceCollection. This
lifetime can be used in stateless service. It is a way to add
lightweight service.
Example
services.AddTransient<IHelloWorldService, HelloWorldService>();
Scoped
ASP.NET Core will create and share an instance of the service per
request to the application. It means that a single instance of service
available per request. It will create a new instance in the new
request. The service can be added as scoped using an AddScoped
method of IServiceCollection. We need to take care while, service
registered via Scoped in middleware and inject the service in the
Invoke or InvokeAsync methods. If we inject dependency via the
constructor, it behaves like singleton object.
services.AddScoped<IHelloWorldService, HelloWorldService>();
1. Describe the ASP.NET Core.
ASP.NET Core is an open-source, cross-platform and high performance platform that
allows you to build modern, Internet-connected and cloud enabled applications. With
ASP.NET Core you can
build web applications, IoT (Internet of things) apps, services and mobile
Backends.
run on .Net Core.
You can do your development on Linux, Windows and MacOS.
deploy your code to cloud or on-premises.
2. 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.
3. What is the role of Startup class?
Startup class is responsible for configuration related things as below.
It configures the services which are required by the app.
It defines the app's request handling pipeline as a series of middleware
components.
// Startup class example
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
// other middleware components
}
}
Startup class is specified inside the 'CreateHostBuilder' method when the host is
created.
Multiple Startup classes can also be defined for different environments, At run time
appropriate startup class is used.
4. What is the role of ConfigureServices and Configure method?
ConfigureServices method is optional and defined inside startup class as mentioned
in above code. It gets called by the host before the 'Configure' method to configure the
app's services.
Configure method is used to add middleware components to the IApplicationBuilder
instance that's available in Configure method. Configure method also specifies how
the app responds to HTTP request and response. ApplicationBuilder instance's 'Use...'
extension method is used to add one or more middleware components to request
pipeline.
You can configure the services and middleware components without the Startup class
and it's methods, by defining this configuration inside the Program class
in CreateHostBuilder method.
5. Describe the Dependency Injection.
Dependency Injection is a Design Pattern that's used as a technique to achieve
the Inversion of Control (IoC) between the classes and their dependencies.
ASP.NET Core comes with a built-in Dependency Injection framework that makes
configured services available throughout the application. You can configure the
services inside the ConfigureServices method as below.
services.AddScoped();
A Service can be resolved using constructor injection and DI framework is responsible
for the instance of this service at run time. For more visit ASP.NET Core Dependency
Injection
6. What problems does Dependency Injection solve?
Let's understand Dependency Injection with this C# example. A class can use a direct
dependency instance as below.
Public class A {
MyDependency dep = new MyDependency();
public void Test(){
dep.SomeMethod();
}
}
But these direct dependencies can be problematic for the following reasons.
If you want to replace 'MyDependency' with a different implementation then
the class must be modified.
It's difficult to Unit Test.
If MyDependency class has dependencies then it must be configured by class.
If Multiple classes have dependency on 'MyDependency', the code becomes
scattered.
DI framework solves these problems as below.
Use Interfaces or base class to abstract the dependency implementation.
Dependencies are registered in the Service Container provided by ASP.NET
Core inside Startup class 'ConfigureServices' method.
Dependencies are injected using constructor injection and the instance is
created by DI and destroyed when no longer needed.
7. Describe the Service Lifetimes.
When Services are registered, there is a lifetime for every service. ASP.NET Core
provide following lifetimes.
Transient - Services with transient lifetime are created each time they are
requested from service container. So it's best suited for stateless, light weight
services.
Scoped - Services with scoped lifetime are created once per connection or
client request. When using scoped service in middleware then inject the service
via invoke or invokeAsync method. You should not inject the service via
constructor injection as it treats the service behavior like Singleton.
Singleton - Service with singleton lifetime is created once when first time the
service is requested. For subsequent requests same instance is served by service
container.
8. Explain the Middleware in ASP.NET Core.
The Request handling pipeline is a sequence of middleware components where each
component performs the operation on request and either call the next middleware
component or terminate the request. When a middleware component terminates the
request, it's called Terminal Middleware as It prevents next middleware from
processing the request. You can add a middleware component to the pipeline by
calling .Use... extension method as below.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
So Middleware component is program that's build into an app's pipeline to handle
the request and response. Each middleware component can decide whether to pass the
request to next component and to perform any operation before or after next
component in pipeline.
9. What is Request delegate?
Request delegates handle each HTTP request and are used to build request pipeline.
It can configured using Run, Map and Use extension methods. An request delegate
can be a in-line as an anonymous method (called in-line middleware) or a reusable
class. These classes or in-line methods are called middleware components.
10. What is Host in ASP.NET Core?
Host encapsulates all the resources for the app. On startup, ASP.NET Core
application creates the host. The Resources which are encapsulated by the host
include:
HTTP Server implementation
Dependency Injection
Configuration
Logging
Middleware components
11. Describe the Generic Host and Web Host.
The host setup the server, request pipeline and responsible for app startup and lifetime
management. There are two hosts:
.NET Generic Host
ASP.NET Core Web Host
.NET Generic Host is recommended and ASP.NET Core template builds a .NET
Generic Host on app startup.
ASP.NET Core Web host is only used for backwards compatibility.
// Host creation
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup();
}
12. Describe the Servers in ASP.NET Core.
Server is required to run any application. ASP.NET Core provides an in-process
HTTP server implementation to run the app. This server implementation listen for
HTTP requests and surface them to the application as a set of request features
composed into an HttpContext.
ASP.NET Core use the Kestrel web server by default. ASP.NET Core comes with:
Default Kestrel web server that's cross platform HTTP server implementation.
IIS HTTP Server that's in-process server for IIS.
HTTP.sys server that's a Windows-only HTTP server and it's based on the
HTTP.sys kernel driver and HTTP Server API.
13. How Configuration works in ASP.NET Core?
In ASP.NET Core, Configuration is implemented using various configuration
providers. Configuration data is present in the form of key value pairs that can be read
by configuration providers as key value from different configuration sources as below.
appsettings.json - settings file
Azure Key Vault
Environment variables
In-memory .Net objects
Command Line Arguments
Custom Providers
By default apps are configured to read the configuration data from appsettings.json,
environment variables, command line arguments etc. While reading the data, values
from environment variables override appsettings.json data values.
'CreateDefaultBuilder' method provide default configuration.
14. How to read values from Appsettings.json file?
You can read values from appsettings.json using below code.
class Test{
// requires using Microsoft.Extensions.Configuration;
private readonly IConfiguration Configuration;
public TestModel(IConfiguration configuration)
{
Configuration = configuration;
}
// public void ReadValues(){
var val = Configuration["key"]; // reading direct key values
var name = Configuration["Employee:Name"]; // read complex values
}
}
Default configuration provider first load the values from appsettings.json and then
from appsettings.Environment.json file.
Environment specific values override the values from appsettings.json file. In
development environment appsettings.Development.json file values override the
appsettings.json file values, same apply to production environment.
You can also read the appsettings.json values using options pattern described Read
values from appsettings.json file.
15. What is the Options Pattern in ASP.NET Core?
Options Pattern allow you to access related configuration settings in Strongly typed
way using some classes. When you are accessing the configuration settings with the
isolated classes, The app should adhere these two principles.
Interface Segregation Principle (ISP) or Encapsulation: The class the
depend on the configurations, should depend only on the configuration settings
that they use.
Separation of Concerns: Settings for different classes should not be related or
dependent on one another.
In ASP.NET Core, the options pattern is a way to manage configuration settings in a
strongly-typed manner. This allows you to bind sections of your configuration (e.g.,
from appsettings.json) to C# classes, making it easier to work with configuration
values throughout your application.
Step-by-Step Guide to Using the Options Pattern
1. Create a Configuration Class
First, define a class that represents the configuration section. For example, if you have
settings related to a database connection:
csharp
Copy code
public class DatabaseSettings
{
public string ConnectionString { get; set; }
public int MaxConnections { get; set; }
}
2. Add Configuration to appsettings.json
Next, add the corresponding section to your appsettings.json file:
json
Copy code
{
"DatabaseSettings": {
"ConnectionString": "Server=myServer;Database=myDB;User
Id=myUser;Password=myPass;",
"MaxConnections": 100
}
}
3. Register the Configuration Class in the Service Container
In Program.cs, bind the configuration section to your class and register it with the
dependency injection (DI) container:
csharp
Copy code
var builder = WebApplication.CreateBuilder(args);
// Bind the DatabaseSettings section to the DatabaseSettings class
builder.Services.Configure<DatabaseSettings>(
builder.Configuration.GetSection("DatabaseSettings"));
var app = builder.Build();
4. Inject the Options into Your Services
You can then inject IOptions<DatabaseSettings> into any class (like controllers or
services) where you need to access these settings:
csharp
Copy code
using Microsoft.Extensions.Options;
public class MyService
{
private readonly DatabaseSettings _dbSettings;
public MyService(IOptions<DatabaseSettings> dbSettings)
{
_dbSettings = dbSettings.Value; // Get the value of the
options
}
public void PrintConnectionString()
{
Console.WriteLine(_dbSettings.ConnectionString);
}
}
// Register the service in Program.cs
builder.Services.AddTransient<MyService>();
5. Using the Options in a Controller
If you want to use these settings in a controller, you can do it like this:
csharp
Copy code
public class MyController : ControllerBase
{
private readonly DatabaseSettings _dbSettings;
public MyController(IOptions<DatabaseSettings> dbSettings)
{
_dbSettings = dbSettings.Value;
}
[HttpGet]
public IActionResult Get()
{
return Ok(_dbSettings.ConnectionString);
}
}
16. How to use multiple environments in ASP.NET Core?
ASP.NET Core use environment variables to configure application behavior based on
runtime environment. launchSettings.json file
sets ASPNETCORE_ENVIRONMENT to Development on local Machine.
In ASP.NET Core, managing multiple environments (such as Development, Staging, and
Production) is straightforward and allows you to configure your application differently based
on the environment it's running in. Here's how to set it up:
Step 1: Define Environments
ASP.NET Core recognizes several environments by default:
Development
Staging
Production
You can also define custom environments if needed.
Step 2: Set the Environment Variable
The environment can be set using the ASPNETCORE_ENVIRONMENT environment variable.
There are several ways to set this variable:
1. Via the Command Line:
o For Windows:
bash
Copy code
set ASPNETCORE_ENVIRONMENT=Development
o For Linux/macOS:
bash
Copy code
export ASPNETCORE_ENVIRONMENT=Development
2. In launchSettings.json (for local development): Open the
Properties/launchSettings.json file in your project and set the environment
variable under the appropriate profile:
json
Copy code
{
"profiles": {
"MyApp": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
3. In Azure or Other Hosting Services: Most cloud services allow you to set
environment variables through their management interfaces.
Step 3: Configuration Files for Each Environment
ASP.NET Core uses configuration files to load settings. You can create environment-specific
configuration files, such as:
appsettings.json (common settings)
appsettings.Development.json
appsettings.Staging.json
appsettings.Production.json
The configuration system automatically loads the appropriate settings based on the current
environment. For example, if the environment is set to Development, it will load settings
from both appsettings.json and appsettings.Development.json.
Step 4: Accessing Environment Information
You can access the current environment in your application using IWebHostEnvironment:
csharp
Copy code
public class Startup
{
private readonly IWebHostEnvironment _env;
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
if (_env.IsDevelopment())
{
// Development-specific services
}
else if (_env.IsProduction())
{
// Production-specific services
}
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
// Other middleware
}
}
Step 5: Using Environment-Specific Code
You can also use conditional statements based on the environment to run specific code:
csharp
Copy code
if (env.IsDevelopment())
{
// Code that runs only in development
}
else if (env.IsStaging())
{
// Code that runs only in staging
}
else
{
// Code for production
}
17. How Logging works in .NET Core and ASP.NET Core?
18. How Routing works in ASP.NET Core?
Routing is used to handle incoming HTTP requests for the app. Routing find
matching executable endpoint for incoming requests. These endpoints are registered
when app starts. Matching process use values from incoming request url to process the
requests. You can configure the routing in middleware pipeline of configure method
in startup class.
app.UseRouting(); // It adds route matching to middlware pipeline
// It adds endpoints execution to middleware pipeline
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
For more you can refer ASP.NET Core Routing
19. How to handle errors in ASP.NET Core?
ASP.NET Core provides a better way to handle the errors in Startup class as below.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
For development environment, Developer exception page display detailed information
about the exception. You should place this middleware before other middlewares for
which you want to catch exceptions. For other
environments UseExceptionHandler middleware loads the proper Error page.
You can configure error code specific pages in Startup class Configure method as
below.
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404)
{
context.Request.Path = "/not-found";
await next();
}
if (context.Response.StatusCode == 403 || context.Response.StatusCode
== 503 || context.Response.StatusCode == 500)
{
context.Request.Path = "/Home/Error";
await next();
}
});
For more visit Error handling
20. How ASP.NET Core serve static files?
In ASP.NET Core, Static files such as CSS, images, JavaScript files, HTML are the
served directly to the clients. ASP.NET Core template provides a root folder
called wwwroot which contains all these static files. UseStaticFiles() method
inside Startup.Configure enables the static files to be served to client.
You can serve files outside of this webroot folder by configuring Static File
Middleware as following.
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(env.ContentRootPath, "MyStaticFiles")), //
MyStaticFiles is new folder
RequestPath = "/StaticFiles" // this is requested path by client
});
// now you can use your file as below
<img src="/StaticFiles/images/profile.jpg" class="img" alt="A red rose" />
// profile.jpg is image inside MyStaticFiles/images folder
23. Explain Session and State management in ASP.NET Core
As we know HTTP is a stateless protocol. HTTP requests are independent and does
not retain user values. There are different ways to maintain user state between
multiple HTTP requests.
Cookies
Session State
TempData
Query strings
Hidden fields
HttpContext.Items
Cache
24. Can ASP.NET Application be run in Docker containers?
Yes, you can run an ASP.NET application or .NET Core application in Docker
containers.
For Docker interview questions visit Docker Questions
For more about .NET and Docker visit .NET and Docker and Docker images
for ASP.NET Core
24. Explain Model Binding in ASP.NET Core.
25. Explain Custom Model Binding.
26. Describe Model Validation.
27. How to write custom ASP.NET Core middleware?
28. How to access HttpContext in ASP.NET Core?
29. Explain the Change Token.
30. How to used ASP.NET Core APIs in class library?
31. What is the Open Web Interface for .NET (OWIN)?
32. Describe the URL Rewriting Middleware in ASP.NET Core.
33. Describe the application model in ASP.NET Core.
ASP.NET Core MVC defines an application model representing the components
of an MVC app. ... By default, MVC follows certain conventions to determine which
classes are considered controllers, which methods on those classes are actions, and
how parameters and routing behave
34. Explain the Caching or Response caching in ASP.NET Core.
Caching significantly improves the performance of an application by reducing the
number of calls to actual data source. It also improves the scalability. Response
caching is best suited for data that changes infrequently. Caching makes the copy of
data and store it instead of generating data from original source.
Response caching headers control the response caching. ResponseCache attribute sets
these caching headers with additional properties.
35. What is In-memory cache?
In-memory cache is the simplest way of caching by ASP.NET Core that stores the
data in memory on web server.
Apps running on multiple server should ensure that sessions are sticky if they are
using in-memory cache. Sticky Sessions responsible to redirect subsequent client
requests to same server. In-memory cache can store any object but distributed cache
only stores byte[].
IMemoryCache interface instance in the constructor enables the In-memory caching
service via ASP.NET Core dependency Injection.
36. What is Distributed caching?
Applications running on multiple servers (Web Farm) should ensure that sessions are
sticky. For Non-sticky sessions, cache consistency problems can occur. Distributed
caching is implemented to avoid cache consistency issues. It offloads the memory to
an external process. Distributed caching has certain advantages as below.
Data is consistent across client requests to multiple server
Data keeps alive during server restarts and deployments.
Data does not use local memory
IDistributedCache interface instance from any constructor enable distributed caching
service via Dependency Injection.
37. What is XSRF or CSRF? How to prevent Cross-Site Request Forgery (XSRF/CSRF)
attacks in ASP.NET Core?
Cross-Site Request Forgery (XSRF/CSRF) is an attack where attacker that acts as a
trusted source send some data to a website and perform some action. An attacker is
considered a trusted source because it uses the authenticated cookie information stored
in browser.
For example a user visits some site 'www.abc.com' then browser performs
authentication successfully and stores the user information in cookie and perform
some actions, In between user visits some other malicious site 'www.bad-user.com'
and this site contains some code to make a request to vulnerable site (www.abc.com).
It's called cross site part of CSRF.
How to prevent CSRF?
In ASP.NET Core 2.0 or later FormTaghelper automatically inject the
antiforgery tokens into HTML form element.
You can add manually antiforgery token in HTML forms by
using @Html.AntiForgeryToken() and then you can validate it in controller
by ValidateAntiForgeryToken() method.
For more you can visit Prevent Cross-Site Request Forgery (XSRF/CSRF)
38. How to prevent Cross-Site Scripting (XSS) in ASP.NET Core?
39. How to enable Cross-Origin Requests (CORS) in ASP.NET Core?
Enabling Cross-Origin Requests (CORS) in ASP.NET Core is straightforward and involves a
few key steps. CORS allows your application to specify which origins can access its
resources, making it crucial for enabling secure interactions between your API and client
applications hosted on different domains.
Steps to Enable CORS in ASP.NET Core
1. Add CORS Services: First, you need to add CORS services in the
ConfigureServices method in your Startup.cs file.
csharp
Copy code
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("https://example.com") // specify the
allowed origin
.AllowAnyHeader() // allow any
header
.AllowAnyMethod(); // allow any
HTTP method
});
});
services.AddControllers(); // or AddMvc() if using MVC
}
2. Use CORS Middleware: Next, apply the CORS policy in the Configure method.
csharp
Copy code
public void Configure(IApplicationBuilder app, IWebHostEnvironment
env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("MyPolicy"); // apply the CORS policy
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // or MapDefaultControllerRoute()
if using MVC
});
}
3. Customizing the CORS Policy: You can customize the CORS policy further based
on your requirements. For instance, you can specify multiple origins, allow
credentials, or limit specific headers and methods.
csharp
Copy code
options.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("https://example.com",
"https://anotherdomain.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials(); // allow credentials if needed
});
4. Using CORS with Controllers: You can also apply CORS policies at the controller
or action level by using the [EnableCors] attribute.
csharp
Copy code
[ApiController]
[Route("api/[controller]")]
[EnableCors("MyPolicy")] // apply CORS policy to this controller
public class MyController : ControllerBase
{
// actions here
}
40. What is the Area?
Area is used to divide large ASP.NET MVC application into multiple functional
groups. In general, for a large application Models, Views and controllers are kept in
separate folders to separate the functionality. But Area is a MVC structure that
separate an application into multiple functional groupings. For example, for an e-
commerce site Billing, Orders, search functionalities can be implemented using
different areas.
41. Explain the Filters.
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.
42. Describe the View components in ASP.NET Core.
43. How View compilation works in ASP.NET Core?
44. Explain Buffering and Streaming approaches to upload files in ASP.NET Core.
ASP.NET Core MVC Interview Questions
1. Describe the ASP.NET Core MVC.
ASP.NET Core MVC is a framework to build web applications and APIs. It's based
on Model-View-Controller (MVC) Design Pattern. This design pattern separate an
application into three main components known as Model, View and Controller. It also
helps to achieve SoC (Separation of Concern) design principle.
ASP.NET Core MVC is light weight, open-source and testable framework to build
web applications and services.
2. Explain the Model, View and Controller.
ASP.NET MVC has three main group of components Model, View and Controller,
Each one has his own responsibilities as below.
Model - It contains the business logic and represents the state of an application.
It also performs the operation on the data and encapsulates the logic to persist
an application state. Strongly-typed Views use View-Model pattern to display
the data in the view.
View - It's responsible to present the content via User interface. It does not
contain much logic and use Razor View Engine to embed .NET code into
view. If you need to perform much logic to display the data then prefer to use
View Component, View Model or View Template for simplify view.
Controller - It's responsible to handle user interactions, It works with model
and select the view to display. Controller is the main entry point that decides
the model with which it works and decide which view it needs to display.
Hence it's name - Controller means controls user inputs and interactions.
3. Explain View-Model.
ViewModel is used to pass a complex data from controller to view. ViewModel data
is prepared from different models and passed to view to display that data. For
example, A Complex data model can be passed with the help of ViewModel.
Class Author{
public int Id {get;set;}
public Book Book {get;set;}
}
Class Book{
public string Name {get;set;}
public string PublisherName {get;set;}
}
This Author and Book data can be passed to view by creating Author ViewModel
inside controller.
4. Explain strongly-typed views.
Strongly-typed views are tightly bound to a model. for example, In above question if
you want to pass the author data to view then you need to write below code for type
checking in your view. @model Author. Controller can pass strongly type model to
view that enables type checking and intelliSense support in view.
5. Explain Partial Views.
6. How routing works in MVC application?
7. Describe Attribute based routing.
Attribute Routing gives you more control over the URIs in your web application.
MVC 5 supports this attribute based routing where attributes are used to define the
routes. You can manage resource hierarchies in better way using attribute based
routing. Attribute based routing is used to create routes which are difficult to create
using convention-based routing. For example below routes.
[Route("customers/{customerId}/orders")]
public IEnumerable GetOrdersByCustomer(int customerId) { ... }
.
.
.
[Route("customers/{customerId}/orders/orderId")]
public IEnumerable GetOrdersByCustomer(int customerId, int orderId) { ... }
8. Explain dependency injection for controllers.
9. How ASP.NET Core supports dependency injection into views?
10. How will you unit test a controller?
11. What is Cache Tag Helper in ASP.NET Core MVC?
The Cache Tag Helper in ASP.NET Core MVC is a feature that allows you to easily
implement output caching for parts of your views. It is useful for improving the performance
of your web applications by caching rendered content and serving it to users without needing
to regenerate it on each request.
Key Features of the Cache Tag Helper
1. Output Caching: It caches the output of a specific section of your view, reducing the
load on your server and improving response times for frequently requested content.
2. Easy Integration: You can use the Cache Tag Helper in Razor views by simply
adding a <cache> tag with attributes to control its behavior.
3. Flexible Duration: You can specify how long the content should be cached, allowing
for fine-tuned control over cache duration.
4. Cache Variation: You can vary the cache based on user-specific conditions or
parameters, such as user roles or query strings.
Basic Usage
Here's how you can use the Cache Tag Helper in your Razor views:
razor
Copy code
<cache duration="60">
<h2>This content is cached for 60 seconds!</h2>
<p>Current time: @DateTime.Now</p>
</cache>
In this example, the content inside the <cache> tag will be cached for 60 seconds. During that
time, any requests for this content will receive the cached version instead of executing the
Razor view logic again.
Attributes
The Cache Tag Helper supports several attributes:
duration: Specifies how long (in seconds) the content should be cached.
vary-by: Specifies how to vary the cache (e.g., by user or query string).
name: Provides a way to name the cached content, allowing for better cache
management.
Example with Varying Cache
You can also vary the cache based on user-specific data:
razor
Copy code
<cache duration="120" vary-by="User.Identity.Name">
<h2>Welcome, @User.Identity.Name!</h2>
<p>Current time: @DateTime.Now</p>
</cache>
In this example, the cached output will vary for different users, meaning each user will see
their own cached version for 120 seconds.
Considerations
Cache Size: Be mindful of the amount of content being cached, as it can consume
server memory.
Dynamic Content: Use caching wisely for content that doesn't change frequently.
Avoid caching content that is highly dynamic or user-specific unless properly
configured.
Invalidation: Consider how you will invalidate or update the cache when underlying
data changes.
12. How validation works in MVC and how they follow DRY Pattern?
13. Describe the complete request processing pipeline for ASP.NET Core MVC.
ASP.NET is a web application framework developed by Microsoft which
was released as part of the .NET framework. It makes it easy to build
dynamic web applications. Some other examples of similar web
application frameworks include Ruby on Rails (Ruby), Django (Python),
and Express (JavaScript).
ASP.NET Core is a cross-platform, high-performance, and open-
source web application framework. Microsoft released the first version of
ASP.NET Core in 2016. It enables developers to create modern, cloud-
enabled applications.
Cross-Platform: The main advantage of ASP.NET Core is that it’s
not tied to a Windows operating system, like the legacy ASP.NET
framework. You can develop and run production-ready ASP.NET
Core apps on Linux or a Mac.
High Performance: It’s designed from scratch, keeping
performance in mind. It’s now one of the fastest web application
frameworks.
Open Source: Finally, it’s open-source and actively contributed by
thousands of developers all over the world.
Both the ASP.NET and ASP.NET Core run on C#, an object-oriented,
general-purpose programming language. ASP.NET Core inherits many
concepts and features from its ASP.NET heritage, but it’s fundamentally a
new framework.
Though Microsoft is going to support the legacy ASP.NET framework, it’s
not going to develop it actively. The new ASP.NET Core framework will
include all the new features and enhancements. Going forward, Microsoft
is recommending developers to build all the new web applications with
ASP.NET Core instead of the legacy ASP.NET framework.
In this article, we will focus on both ASP.NET and ASP.NET Core interview
questions. To limit the article’s scope, we assume that you have
programmed in the C# programming language. A basic understanding of
common object-oriented concepts and front-end technologies such as
HTML, CSS, and JavaScript is also expected.
We have divided the interview questions into two sections. The basic
interview questions cover the fundamentals and focus on understanding
the application structure of a basic ASP.NET project. Then, we cover the
more advanced concepts such as dependency injection, routing, and
model binding in the advanced interview questions.
Basic ASP.NET Interview Questions
1. What is a web application?
A Web application is a software that the users can access through a web
browser such as Chrome or Firefox. The browser makes an HTTP request
for a specific URL for the web application. The web application server
intercepts and processes the request to build a dynamic HTML response
sent to the user. Some examples of popular web applications include
StackOverflow, Reddit, Google, etc.
A web application is different from a typical website. A website is static.
When you go to the website, it returns an HTML page without doing any
processing to build the contents of that HTML page. You will see the
same page if you reload the browser. In contrast, a web application
might return a different response each time you visit.
For example, let’s say you ask a question on Stack Overflow. Initially, you
will see only your question when you visit the URL. However, if another
user answers your question, the browser will display that answer on your
next visit to the same URL.
A web application consists of multiple separate layers. The typical
example is a three-layered architecture made up of presentation,
business, and data layers. For example, the browser (presentation) talks
to the application server, which communicates to the database server to
fetch the requested data.
The following figure illustrates a typical Web application architecture
with standard components grouped by different areas of concern.
2. What is a web application framework, and what are its
benefits?
Learning to build a modern web application can be daunting. Most of the
web applications have a standard set of functionality such as:
Build a dynamic response that corresponds to an HTTP request.
Allow users to log into the application and manage their data.
Store the data in the database.
Handle database connections and transactions.
Route URLs to appropriate methods.
Supporting sessions, cookies, and user authorization.
Format output (e.g. HTML, JSON, XML), and improve security.
Frameworks help developers to write, maintain and scale applications.
They provide tools and libraries that simplify the above recurring tasks,
eliminating a lot of unnecessary complexity.
3. What are some benefits of ASP.NET Core over the
classic ASP.NET?
Cross-Platform: The main advantage of ASP.NET Core is that it’s
not tied to a Windows operating system, like the legacy ASP.NET
framework. You can develop and run production-ready ASP.NET
Core apps on Linux or a Mac. Choosing an open-source operating
system like Linux results in significant cost-savings as you don’t
have to pay for Windows licenses.
High Performance: It’s also designed from scratch, keeping
performance in mind. It’s now one of the fastest web application
frameworks.
Open Source: Finally, it’s open-source and actively contributed by
thousands of developers all over the world. All the source code is
hosted on GitHub for anyone to see, change and contribute back. It
has resulted in significant goodwill and trust for Microsoft,
notwithstanding the patches and bug-fixes and improvements
added to the framework by contributors worldwide.
New Technologies: With ASP.NET Core, you can develop
applications using new technologies such as Razor Pages and
Blazor, in addition to the traditional Model-View-Controller
approach.
4. When do you choose classic ASP.NET over ASP.NET
Core?
Though it’s a better choice in almost all the aspects, you don’t have to
switch to ASP.NET Core if you are maintaining a legacy ASP.NET
application that you are happy with and that is no longer actively
developed.
ASP.NET MVC is a better choice if you:
Don’t need cross-platform support for your Web app.
Need a stable environment to work in.
Have nearer release schedules.
Are already working on an existing app and extending its
functionality.
Already have an existing team with ASP.NET expertise.
5. Explain how HTTP protocol works?
Hypertext Transfer Protocol (HTTP) is an application-layer protocol for
transmitting hypermedia documents, such as HTML. It handles
communication between web browsers and web servers. HTTP follows a
classical client-server model. A client, such as a web browser, opens a
connection to make a request, then waits until it receives a response
from the server.
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.
6. What is a web server?
The term web server can refer to both hardware or software, working
separately or together.
On the hardware side, a web server is a computer with more processing
power and memory that stores the application’s back-end code and
static assets such as images and JavaScript, CSS, HTML files. This
computer is connected to the internet and allows data flow between
connected devices.
On the software side, a web server is a program that accepts HTTP
requests from the clients, such as a web browser, processes the request,
and returns a response. The response can be static, i.e. image/text, or
dynamic, i.e. calculated total of the shopping cart.
Popular examples of web servers include Apache, Nginx, IIS.
7. What is the MVC pattern?
The Model-View-Controller (MVC) is an architectural pattern that
separates an application into three main logical components: the model,
the view, and the controller. It’s different to note that this pattern is
unrelated to the layered pattern we saw earlier. MVC pattern operates on
the software side, while the layered pattern dictates how and where we
place our database and application servers.
In an application that follows the MVC pattern, each component has its
role well specified. For example, model classes only hold the data and
the business logic. They don't deal with HTTP requests. Views only
display information. The controllers handle and respond to user input and
decide which model to pass to which view. This is known as the
separation of responsibility. It makes an application easy to develop and
maintain over time as it grows in complexity.
Though Model-View-Controller is one of the oldest and most prominent
patterns, alternate patterns have emerged over the years. Some popular
patterns include MVVM (Model-View-ViewModel), MVP (Model-View-
Presenter), MVA (Model-View-Adapter).
8. Explain the role of the various components of the MVC
pattern?
Model: Represents all the data and business logic that the user works
within a web application. In ASP.NET, the model is represented by C#
classes that hold the data and the related logic that operates on that
data. The 'Models' directory stores the model classes.
For example, a model class representing a blog post might look like this:
// Models/Post.cs
namespace app.Models
{
public class Post
{
public int ID { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
View: Represents all the UI logic of the application. In a web application,
it represents the HTML that's sent to the user and displayed in the
browser.
One important thing to remember is that this HTML is not static or hard-
coded. It's generated dynamically by the controller using a model's data.
In ASP.NET, the 'Views' directory contains the views in files ending with
the .cshtml file extension.
To continue our example of a blog post, a view to render a post might
be:
// Views/Post.cshtml
<div class="post">
<div class="title">
<a href="/posts/@post.ID">@post.Title</a>
</div>
<div class=body>
@Html.Raw(post.Body)
</div>
</div>
Controller: Acts as an interface between Model and View. It processes
the business logic and incoming requests, manipulates data using the
Model, and interacts with the Views to render the final output.
In ASP.NET, these are C# classes that form the glue between a model
and a view. They handle the HTTP request from the browser, then
retrieve the model data and pass it to the view to dynamically render a
response. The 'Controllers' directory stores the controller classes.
A PostController that builds the view for the post by fetching the Post
model will be:
// Controllers/PostController
namespace app.Controllers
{
public class PostsController : BaseController
{
public IActionResult Post(int id)
{
// Get the post from the database
Post post = _service.Get(id);
// Render the post.cshtml view, by providing the post model
return View(post);
}
}
}
9. What is the purpose of the .csproj file?
The project file is one of the most important files in our application. It
tells .NET how to build the project.
All .NET projects list their dependencies in the .csproj file. If you have
worked with JavaScript before, think of it like a package.json file. The
difference is, instead of a JSON, this is an XML file.
When you run dotnet restore, it uses the .csproj file to figure out which
NuGet packages to download and copy to the project folder (check out
the next question to learn more about Nuget).
The .csproj file also contains all the information that .NET tooling needs
to build the project. It includes the type of project you are building
(console, web, desktop, etc.), the platform this project targets, and any
dependencies on other projects or 3rd party libraries.
Here is an example of a .csproj file that lists the Nuget packages and
their specific versions.
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.S3" Version="3.5.6.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite"
Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory"
Version="5.0.0" />
<PackageReference Include="Npgsql" Version="5.0.1.1" />
<PackageReference Include="Serilog" Version="2.10.0" />
</ItemGroup>
</Project>
In the above example,
The SDK attribute specifies the type of .NET project.
TargetFramework is the framework this application will run
on, .NET 5 in this case.
The PackageReference element includes the NuGet packages. The
Version attribute specifies a version of the package we want.
10. What is NuGet package manager?
Software developers don’t write all code from scratch. They rely on
libraries of code written by other developers. Any modern development
platform must provide a mechanism where developers can download and
use existing libraries, often called packages. For example, the JavaScript
ecosystem has NPM (Node Package Manager), where developers can find
and use libraries written by other JavaScript developers.
NuGet is a package manager for the .NET ecosystem. Microsoft
developed it to provide access to thousands of packages written by .NET
developers. You can also use it to share the code you wrote with others.
A typical web application developed using ASP.NET relies on many open
source NuGet packages to function. For example, Newtonsoft.Json is a
very popular package (with 91,528,205 downloads at the time of writing)
used to work with JSON data in .NET.
11. What is the purpose of the Program class?
Program.cs class is the entry point of our application. An ASP.NET
application starts in the same way as a console application, from
a static void Main() function.
This class configures the web host that will serve the requests. The host
is responsible for application startup and lifetime management, including
graceful shutdown.
At a minimum, the host configures a server and a request processing
pipeline. The host can also set up logging, configuration, and
dependency injection.
12. What is the purpose of the Startup class?
This class handles two important aspects of your application, namely
service registration, and middleware pipeline.
Services are C# classes that your application depends on for providing
additional functionality, both used by the framework and your
application. Examples include logging, database, etc. These services
must be registered to be instantiated when your app is running and
when it needs them.
The middleware pipeline is the sequence in which your application
processes an HTTP request (the next question explains the concept of
Middleware in detail).
Startup class contains two
methods: ConfigureServices() and Configure(). As the name
suggests, the first method registers all the services that the application
needs. The second method configures the middleware pipeline.
13. What is the purpose of the wwwroot folder?
The wwwroot folder contains static files and compiled assets, such as
JavaScript, CSS, and images that your web application needs. Wwwroot is
the only folder in the entire project that's exposed as-is to the browser.
14. What is the purpose of the appsettings.json file?
Appsettings.json contains all of the application's settings, which allow
you to configure your application behavior.
Here is an example of an appsettings.json file.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"AppConnection": ""
},
"AWS": {
"Profile": "local-test-profile",
"Region": "us-west-2"
},
"AllowedHosts": "*"
}
15. What is IIS?
IIS stands for Internet Information Services. It is a powerful web server
developed by Microsoft. IIS can also act as a load balancer to distribute
incoming HTTP requests to different application servers to allow high
reliability and scalability.
It can also act as a reverse proxy, i.e. accept a client’s request, forward it
to an application server, and return the client’s response. A reverse
proxy improves the security, reliability, and performance of your
application.
A limitation of IIS is that it only runs on Windows. However, it is very
configurable. You can configure it to suit your application’s specific
needs.
16. What is Kestrel?
Kestrel is an open-source, cross-platform web server designed for
ASP.NET Core. Kestrel is included and enabled by default in ASP.NET
Core. It is very light-weight when compared with IIS.
Kestrel can be used as a web server processing requests directly from a
network, including the Internet.
Though Kestrel can serve an ASP.NET Core application on its own,
Microsoft recommends using it along with a reverse proxy such as IIS,
Nginx, or Apache, for better performance, security, and reliability.
17. What is the difference between IIS and Kestrel? Why
do we need two web servers?
The main difference between IIS and Kestrel is that Kestrel is a cross-
platform server. It runs on Windows, Linux, and Mac, whereas IIS only
runs on Windows.
Another essential difference between the two is that Kestrel is fully open-
source, whereas IIS is closed-source and developed and maintained only
by Microsoft.
IIS is very old software and comes with a considerable legacy and bloat.
With Kestrel, Microsoft started with high-performance in mind. They
developed it from scratch, which allowed them to ignore the
legacy/compatibility issues and focus on speed and efficiency.
However, Kestrel doesn’t provide all the rich functionality of a full-
fledged web server such as IIS, Nginx, or Apache. Hence, we typically use
it as an application server, with one of the above servers acting as a
reverse proxy.
18. What is caching?
Caching is the process of storing data in a temporary storage location
that is quicker to access than the original location of the data so that it
can be accessed more quickly when the same data is needed next time.
Caching improves the scalability and performance of your application. It
does this by reducing the work required to fetch the data. Caching is
useful for data that doesn’t change frequently and is expensive to create
and retrieve.
ASP.NET provides a set of caching features out of the box. You can use
the IMemoryCache interface for simple use cases. It represents a cache
stored in the web server’s memory. ASP.NET also supports distributed
caching, which is a cache shared by multiple app servers, with Redis.
Advanced ASP.NET Interview Questions
19. What is model binding in ASP.NET?
Controllers and views need to work with data that comes from HTTP
requests. For example, routes may provide a key that identifies a record,
and posted form fields may provide model properties. The process of
converting these string values to .NET objects could be complicated and
something that you have to do with each request. Model binding
automates and simplifies this process.
The model binding system fetches the data from multiple sources such
as form fields, route data, and query strings. It also provides the data to
controllers and views in method parameters and properties, converting
plain string data to .NET objects and types in the process.
Example:
Let’s say you have the following action method on the PostsController
class:
[HttpGet("posts/{id}")]
public ActionResult<Post> GetById(int id, bool archivedOnly)
And the app receives a request with this URL:
http://yourapp.com/api/Posts/5?ArchivedOnly=true
After the routing selects the action method, model binding executes the
following steps.
Locate the first parameter of GetByID, an integer named id, look
through the available sources in the HTTP request and find id = "5"
in route data.
Convert the string "5" into an integer 5.
Find the next parameter of GetByID, a boolean named
archivedOnly.
Look through the sources and find "ArchivedOnly=true" in the
query string. It ignores the case when matching the parameters to
the strings.
Convert the string "true" into boolean true.
Some other examples of attributes include:
1. [FromQuery] - Gets values from the query string.
2. [FromRoute] - Gets values from route data.
3. [FromForm] - Gets values from posted form fields.
4. [FromBody] - Gets values from the request body.
5. [FromHeader] - Gets values from HTTP headers.
20. What is an Action Method?
An action method is a method in a controller class with the following
restrictions:
1. It must be public. Private or protected methods are not allowed.
2. It cannot be overloaded.
3. It cannot be a static method.
An action method executes an action in response to an HTTP request.
For example, here is an example of an Index() action method on the
PostController. It takes an id as an input and returns an IActionResult,
which can be implemented by any result classes (see the following
question).
public class PostController : Controller
{
public IActionResult Index(int id)
{
}
}
21. What are the different types that implement the
IActionResult interface?
ASP.NET Core has many different types of IActionResult:
ViewResult—Generates an HTML view.
PartialViewResult
RedirectResult—Sends a 302 HTTP redirect response to send a user
to a specified URL automatically.
RedirectToRouteResult—Sends a 302 HTTP redirect response to
automatically send a user to another page, where the URL is
defined using routing.
FileResult—Returns a file as the response.
ContentResult—Returns a provided string as the response.
StatusCodeResult—Sends a raw HTTP status code as the response,
optionally with associated response body content.
NotFoundResult—Sends a raw 404 HTTP status code as the
response.
22. What’s the HTTPContext object? How can you access
it within a Controller?
HTTPContext encapsulates all HTTP-specific information about an
individual HTTP request. You can access this object in controllers by
using the ControllerBase.HttpContext property:
public class HomeController : Controller
{
public IActionResult About()
{
var pathBase = HttpContext.Request.PathBase;
...
return View();
}
}
23. What is dependency injection?
Dependency injection is a design pattern that helps to develop loosely
coupled code. This pattern is used extensively in ASP.NET.
Dependency injection means providing the objects that an object needs
(its dependencies) in that object’s constructor instead of requiring the
object to construct them.
Dependency injection reduces and often eliminates unnecessary
dependencies between objects that don’t need to know each other. It
also helps in testing by mocking or stubbing out the dependencies at
runtime.
24. Explain how dependency injection works in ASP.NET
Core?
ASP.NET Core injects instances of dependency classes by using the built-
in IoC (Inversion-of-Control) container. This container is represented by
the IServiceProvider interface that supports constructor injection.
The types (classes) managed by the container are called services. To let
the IoC container automatically inject our services, we first need to
register them with the IoC container in the Startup class.
ASP.NET Core supports two types of services, namely framework and
application services. Framework services are a part of ASP.NET Core
framework such as ILoggerFactory, IApplicationBuilder,
IHostingEnvironment, etc. In contrast, a developer creates
the application services (custom types or classes) specifically for the
application.
25. What is a cookie?
A cookie is a small amount of data that is persisted across requests and
even sessions. Cookies store information about the user. The browser
stores the cookies on the user’s computer. Most browsers store the
cookies as key-value pairs.
Write a cookie in ASP.NET Core:
Response.Cookies.Append(key, value);
Delete a cookie in ASP.NET Core
Response.Cookies.Delete(somekey);
26. Explain the concept of middleware in ASP.NET Core?
In general, middleware is plumbing software that facilitates
communication flow between two components. In a web application
framework, middleware provides common services and capabilities to
the application outside of the default framework.
In ASP.NET Core, middleware refers to the C# classes that manipulate an
HTTP request when it comes in or an HTTP response when it’s on its way
out. For example,
Generate an HTTP response for an incoming HTTP request
Intercept and make changes to an incoming HTTP request and pass it on
to the next piece of middleware.
Intercept and make changes to an outgoing HTTP response, and pass it
on to the next piece of middleware.
One of the most common use cases for middleware is to deal with
concerns that affect your entire application. These aspects of your
application need to occur with every request, regardless of the specific
path in the request or the resource requested. These include things like
logging, security, authentication, authorization, etc.
For example, logging middleware logs when a request comes in and
passes it to another piece of middleware. Some other common
middleware uses include database middleware, error handling
middleware, and authentication/authorization middleware.
In each of these examples, the middleware receives a request, modifies
it, and then passes it to the next middleware piece in the pipeline.
Subsequent middleware uses the details added by the earlier
middleware to handle the request in some way. The following diagram
illustrates this.
27. What is routing, and how can you define routes in
ASP.NET Core?
Routing is the process of mapping an incoming HTTP request to a specific
method in the application code. A router maps the incoming requests to
the route handler. It takes in a URL as an input and deconstructs it to
determine the controller and action method to route the request.
A simple routing pattern, for example, might determine that
the /posts/show URL maps to the Show action method on
the PostsController.
There are two ways to define routes in an ASP.NET Core MVC
application.
Conventional Routing
Attribute-Based Routing.
We can use both Conventional Routing and Attribute Routing in an
application.
28. Explain how conventional routing works?
As the name suggests, conventional routing uses predefined conventions
to match the incoming HTTP request to a controller’s action method. It
handles the most general cases that a typical web application needs, but
you can modify it to suit your specific needs.
For example, the Configure() method in the Startup.cs class contains the
following code that sets up the conventional routing.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
This code creates a single route named ‘default’. The route template
pattern ‘{controller=Home}/{action=Index}/{id?}’ is used to match an
incoming URL such as /Posts/Archived/5 to the Archived(int id) action
method on the PostsController, passing 5 for the id parameter. By
default, the router uses the Index method on the HomeController.
29. Explain how attribute-based routing works?
Attribute routing is an alternative routing strategy for conventional
routing. It is often used to create REST API endpoints for web services. It
uses a set of attributes to map action methods directly to route
templates.
Attribute routing directly defines the routes on action methods. We can
also use these attributes on the controllers. It enables us to get fine-
grained control over what routes map to which actions. With attribute
routing, the controller and action names play no part in determining the
action method.
For example, we use attributes Blog and Home to map an incoming URL
such as myapp.com/blog/post/3 to the Show method on
the PostsController.
[Route("blog")]
public class PostsController : Controller
{
[HttpGet("post/{id:int}")]
public IActionResult Show(int id = 0)
{
Post post = new Post()
{
ID = id
};
return View("Show", post);
}
[HttpGet("edit/{id:int}")]
public IActionResult Edit(int id)
{
Post postToEdit = _service.Get(id);
return View("Edit", postToEdit);
}
}
In the above example, the attribute [Route(“blog”)] is placed on the
controller, whereas the route [HttpGet(“post/{id:int}”)] is placed on
the action method. A controller route applies to all actions in that
controller. For example, the second [“edit/{id:int}”] route matches the
url myapp.com/blog/edit/3.
In addition to the above route templates, ASP.NET Core provides the
following HTTP verb templates.
[HttpGet]
[HttpPost]
[HttpPut]
[HttpDelete]
[HttpHead]
[HttpPatch]
30. What is a RESTful Web Service or a Web API?
Not all web applications return an HTML view as a response to an HTTP
request. Sometimes, a client only wants some data from your
application, and it wants to handle how that data will be formatted.
For example, let's say your application supports both web and mobile
interfaces. Instead of writing two separate projects which return HTML
and mobile views, you can write a single application that only returns the
specific data that the clients need. Once the clients receive this data,
they format it accordingly. The web client renders the HTML using view
templates and JavaScript, and the mobile clients generate the
appropriate mobile view for its specific platform.
An application might also need to communicate with another application
to fetch the data that it needs. For example, when you go to
Amazon.com, it communicates with hundreds of other services and
applications to retrieve data and renders the final HTML page you see.
Such back-end applications, which provide data, are commonly known as
RESTful web services. REST protocol uses verbs like GET, POST, PUT,
DELETE to communicate between multiple applications. The client and
server can be written in different languages and technologies and still
work together without knowing about each other, as long as each side
knows the format of the data that is getting sent.
ASP.NET Core supports creating RESTful services, also known as web
APIs, using C#. A Web API consists of one or more controllers that derive
from ControllerBase class.
[PostController]
[Route("[controller]")]
public class PostController : ControllerBase
An MVC controller derives from the Controller class. However, a Web
API controller should derive from the ControllerBase class. The reason is
that Controller derives from ControllerBase and provides additional
support for views, which you don’t need for web API requests.
That said, you can use a controller for both rendering views and data.
That is, it can act as both an MVC controller and a Web API controller. In
this case, you can derive the controller from the Controller class.
31. What is Entity Framework?
Most applications require storing and retrieving data. Usually, we store
this data in a database. Working with databases can often be rather
complicated. You have to manage database connections, convert data
from your application to a format the database can understand, and
handle many other subtle issues.
The .NET ecosystem has libraries you can use for this, such as ADO.NET.
However, it can still be complicated to manually build SQL queries and
convert the data from the database into C# classes back and forth.
EF, which stands for Entity Framework, is a library that provides an
object-oriented way to access a database. It acts as an object-relational
mapper, communicates with the database, and maps database
responses to .NET classes and objects.
Entity Framework (EF) Core is a lightweight, open-source, and
cross-platform version of the Entity Framework.
Here are the essential differences between the two:
Cross-platform:
We can use EF Core in cross-platform apps that target .NET Core.
EF 6.x targets .NET Framework, so you’re limited to Windows.
Performance:
EF Core is fast and lightweight. It significantly outperforms EF 6.x.
Features:
EF Core has some features that EF 6.x doesn’t have (batching
statements, client-side key generation, in-memory database for
testing)
EF 6.x is much more feature-rich than EF Core. EF Core is missing
some headline features at the time of writing, such as lazy-loading
and full server-side Group By. However, it is under active
development, so those features will no doubt appear soon
Q. What is .NET Core?
Ans: .NET Core is a newer version of .NET, which is cross-platform,
supporting Windows, MacOS and Linux, and can be used in device,
cloud, and embedded/IoT scenarios.
The following characteristics best define .NET Core:
Flexible deployment: Can be included in your app or
installed side-by-side user or machine-wide.
Cross-platform: Runs on Windows, MacOS and Linux; can be
ported to other OSes. The supported Operating Systems (OS),
CPUs and application scenarios will grow over time, provided
by Microsoft, other companies, and individuals.
Command-line tools: All product scenarios can be exercised
at the command-line.
Compatible: .NET Core is compatible with .NET Framework,
Xamarin and Mono, via the .NET Standard Library.
Q. How is it different from existing .NET framework?
Ans: Read Difference between .NET Core and .NET Framework
Q. What are .NET Platform Standards?
Ans: Read .NET Platform Standards
Q. What is ASP.NET Core?
Ans: ASP.NET Core 1.0 is the next version of ASP.NET. It is open
source and cross-platform framework (supports for Windows, Mac
and Linux) suitable for building cloud based internet connected
applications like web apps, IoT apps and mobile apps. ASP.NET Core
apps can run on .NET Core or on the full .NET Framework.
Q. What are the newly introduced functionalities in ASP.NET Core?
Ans: Read Quick summary of what’s changed in ASP.NET Core.
ASP.NET Core 2.0 is already out and there are few changes and new
things introduced. Read What’s new in ASP.NET Core 2
Q. Why Use ASP.NET Core for Web Application Development?
Ans: ASP.NET Core is an robust, and feature-rich framework that
provides features to develop super-fast APIs for web apps. ASP.NET
Core should be prefered for following reason:
ASP.NET Core is faster compare to traditional ASP.NET.
Cross-platform: Runs on Windows, MacOS and Linux; can be
ported to other OSes. The supported Operating Systems (OS),
CPUs and application scenarios will grow over time, provided
by Microsoft, other companies, and individuals.
Flexible deployment: Can be included in your app or
installed side-by-side user or machine-wide. Runs on IIS or can
be self-hosted in your own process.
Built-in support for dependency injection.
ASP.NET Core is cloud-ready and has improved support for
cloud deployment.
Provides Support for Popular JavaScript Frameworks.
Unification Of Development Models which allows the MVC and
Web API development models to use the same base class
Controller.
Razor Pages makes coding page-focused scenarios easier and
more productive.
Environment based configuration supported for cloud
deployment.
Built in logging support.
In ASP.NET we had modules and handlers to deal with
requests. In ASP.NET Core we have middleware which provides
more control how the request should be processed as they are
executed in the order in which they are added.
Q. What is ASP.NET Core Middleware and How it is different from
HttpModule?
Ans: Read my post about How ASP.NET Core 1.0 Middleware is
different from HttpModule
Q. What are the various JSON files in ASP.NET Core?
Ans: Read my post about Various JSON files in ASP.NET Core
Q. What is Startup.cs file in ASP.NET Core?
Ans: In ASP.NET, Global.asax (though optional) acts as the entry
point for your application. Startup.cs, it is entry point for application
itself. The Startup class configures the request pipeline that handles
all requests made to the application. Read this read this excellent
post The Startup.cs File in ASP.NET Core 1.0 – What Does It Do? to
know more about startup.cs.
Q.What ConfigureServices() method does in Startup.cs?
Ans: This method is optional. It is the place to add services required
by the application. For example, if you wish to use Entity Framework
in your application then you can add in this method.
1
public void ConfigureServices(IServiceCollection services)
2 {
3 services.Configure<AppSettings>(Configuration.GetSubKey("AppSettings"));
4 services.AddEntityFramework()
5 .AddSqlServer()
6 .AddDbContext<SchoolContext>();
// Add MVC services to the services container.
7 services.AddMvc();
8 }
9
Q.What Configure() method does in Startup.cs?
Ans: The Configure method is used to specify how the ASP.NET
application will respond to HTTP requests. The request pipeline is
configured by adding middleware components to an
IApplicationBuilder instance that is provided by dependency
injection. There are some built-in middlewares for error handling,
authentication, routing, session and diagnostic purpose. Highlighted
lines in below code, are built-in Middleware with ASP.NET Core 1.0.
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFact
{
2
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
3 loggerFactory.AddDebug();
4
5
6
7
8 app.UseApplicationInsightsRequestTelemetry();
9
10 if (env.IsDevelopment())
11 {
app.UseBrowserLink();
12 app.UseDeveloperExceptionPage();
13 }
14 else
15 {
16 app.UseExceptionHandler("/Home/Error");
17
// For more details on creating database during deployment see http://go.micr
18 try
19 {
20 using (var serviceScope = app.ApplicationServices.GetRequiredService<IS
21 .CreateScope())
22 {
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
23 .Database.Migrate();
24 }
25 }
26 catch { }
}
27
28 app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear(
29 app.UseStaticFiles();
30 app.UseIdentity();
31
32 // To configure external authentication please see http://go.microsoft.com/fwlink/?L
33 app.UseMvc(routes =>
34 {
35 routes.MapRoute(
36 name: "default",
37 template: "{controller=Home}/{action=Index}/{id?}");
});
38 }
39
40
41
42
Q.What is the difference between app.Use vs app.Run while adding
middleware?
Ans: Read app.Use vs app.Run in ASP.NET Core middleware.
Q.What is the difference between services.AddTransient and
service.AddScope methods are Asp.Net Core?
Ans:ASP.NET Core out of the box supports dependency injection.
These 3 methods allows to register the dependency. However, they
offers different lifetime for registered service. Transient objects are
created for every request (when requested). This lifetime works best
for lightweight, stateless services. Scoped objects are the same
within a request, but different across different
requests. Singleton objects created the first time they’re requested
(or when ConfigureServices is run and an instance is specified with
the service registration).
Q.What is Kestral?
Ans: Kestrel is a cross-platform web server for ASP.NET Core based
on libuv, a cross-platform asynchronous I/O library. Kestrel is the
web server that is included by default in ASP.NET Core new project
templates. If your application accepts requests only from an internal
network, you can use Kestrel by itself.
If you expose your application to the Internet, you must use IIS,
Nginx, or Apache as a reverse proxy server. A reverse proxy server
receives HTTP requests from the Internet and forwards them to
Kestrel after some preliminary handling. The most important reason
for using a reverse proxy for edge deployments (exposed to traffic
from the Internet) is security. Kestrel is relatively new and does not
yet have a full complement of defenses against attacks.
Q.What is WebListener?
Ans: ASP.NET Core ships two server
implementations Kestral and WebListener. WebListener is also a
web server for ASP.NET Core that runs only on Windows. It’s built on
the Http.Sys kernel mode driver. WebListener is an alternative to
Kestrel that can be used for direct connection to the Internet without
relying on IIS as a reverse proxy server.
Q.What is ASP.NET Core Module (ANCM)?
Ans: ASP.NET Core Module (ANCM) lets you run ASP.NET Core
applications behind IIS and it works only with Kestrel; it isn’t
compatible with WebListener. ANCM is a native IIS module that
hooks into the IIS pipeline and redirects traffic to the backend
ASP.NET Core application. ASP.NET Core applications run in a
process separate from the IIS worker process, ANCM also does
process management. ANCM starts the process for the ASP.NET Core
application when the first request comes in and restarts it when it
crashes. In short, it sits in IIS and routes the request for ASP.NET
Core application to Kestral.
Q.What are different ASP.NET Core diagnostic middleware and how
to do error handling?
Ans: Read Various ASP.NET Core Diagnostics Middleware.
Q.What is a Host and what’s the importance of Host in ASP.NET
Core application?
Ans: ASP.NET Core apps require a host in which to execute. The
host is responsible for application startup and lifetime management.
Other responsibility of host’s includes ensuring the application’s
services and the server are available and properly configured. Don’t
confuse yourself with a Server. The host is responsible for
starting the app and its management, where the server is
responsible for accepting HTTP requests. The host is configured to
use a particular server; the server is unaware of its host.
The host is typically created using an instance of a WebHostBuilder,
which builds and returns a WebHost instance. The WebHost references
the server that will handle requests.
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirect
ory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
view rawnetcore1.1_program.cs hosted with by GitHub
In ASP.NET Core 2.0, it is changed. It looks like this:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[]
args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
view rawnetcore2.0_program.cs hosted with by GitHub
Read this post to know more.
Q. What does WebHost.CreateDefaultBuilder() do?
Ans: This method does the following things.
Configure the app to use Kestrel as web server.
Specify to use the current project directory as root directory for
the application.
Setup the configuration sub-system to read setting from
appsettings.json and appsettings.{env}.json to environment
specific configuration.
Set Local user secrets storage only for the development
environment.
Configure environment variables to allow for server-specific
settings.
Configure command line arguments (if any).
Configure logging to read from the Logging section of the
appsettings.json file and log to the Console and Debug window.
Configure integration with IIS
Configure the default service provider.
You can take a look at the code of this method here.
Q.What is the role of IHostingEnvironment interface in ASP.NET
Core?
Ans: ASP.NET Core offers an interface named IHostingEnvironment,
allows you to programmatically retrieve the current environment so
you can have an environment-specific behaviour. By default,
ASP.NET Core has 3 environments Development, Staging, and
Production. Previously, the developers have to build the application
differently for each environment (Staging, UAT, Production) due to
dependency on config file sections and the preprocessor directive
applicable at compile time. ASP.NET Core takes a different approach
and uses IHostingEnvironment to retrieve the current environment.
You can also define a custom environment like QA or UAT.
Q.How to handle 404 error in ASP.NET Core 1.0?
Ans: Read How to handle 404 error in ASP.NET Core 1.0
Q.What is the use of UseIISIntegration?
Ans: This tells ASP.NET that IIS will be working as a reverse proxy in
front of Kestrel. As if you expose your application to the Internet,
you must use IIS, Nginx, or Apache as a reverse proxy server. When
you wish to deploy your ASP.NET Core application on windows, you
need to tell ASP.NET Core Host to use IIS integration.
UseKestrel and UseIISIntegration must be used in conjunction
as UseKestrel creates the web server and hosts the
code. UseIISIntegration specifies IIS as the reverse proxy server.
1 var host = new WebHostBuilder()
2 .UseKestrel()
3 .UseContentRoot(Directory.GetCurrentDirectory())
4 .UseIISIntegration()
.UseStartup<Startup>()
5
.Build();
6
Note that code making call to UseIISIntegration() does not affect
code portability.
Q.What are the different ways for bundling and minification in
ASP.NET Core?
Ans: There are different ways for doing bundling and minification in
ASP.NET Core.
Gulp – was the default choice for ASP.NET Core till beta
versions. Later it was removed due to performance and speed
issue and replaced with BundlerMinifier. Read this post to find
out the reasons of this decision.
BundlerMinifier – is a Visual Studio extension and it’s default
choice now. You should see bundleconfig.json file in your
default template. Read this post to know more about bundling
and minification in ASP.NET Core.
ASP.NET Core Web Optimizer – ASP.NET Core middleware for
bundling and minification of CSS and JavaScript files at
runtime.
Grunt – can also be used with ASP.NET Core.
For more Read Overview of Tools for bundling and minification in
ASP.NET Core.
Q.What is launchsetting.json in ASP.NET Core?
Ans: Read Launchsetting.json in ASP.NET Core
Q.What is wwwroot folder in ASP.NET Core?
Ans: In ASP.NET Core, all the static resources, such as CSS,
JavaScript, and image files are kept under the wwwroot folder
(default). You can also change the name of this folder.
Q.What is “Razor pages” in ASP.NET Core?
Ans: “Razor Pages” is a new feature of ASP.NET Core and it was
released with ASP.NET Core 2.0 release. Razor Pages are simple
pages or views without controllers and introduced with the intent of
creating page focused scenarios where there is no real logic is
involved. You will find razor pages similar to ASP.NET Web Forms.
They work on the convention and need to be placed in Pages folder
and the extension is .cshtml. Razor pages uses handler methods to
deal with incoming HTTP request. Read this post to find out more
about handler methods.
Q.What is tag helper in ASP.NET Core?
Ans: Tag Helpers enable server-side code to participate in creating
and rendering HTML elements in Razor files. For example, the built-
in ImageTagHelper can append a version number to the image name.
There are many built-in tag helpers like From, Image, Anchor and
many others. Read How to use image tag helper in ASP.NET
Core and How to use select tag helper in ASP.NET Core. Read more
about Tag Helpers @ official documentation.
Q.What’s new in .NET Core 2.1 and ASP.NET Core 2.1?
Ans: .NET Core 2.1 and ASP.NET Core 2.1 brings lots of new features
on the table. Read New features of .NET Core 2.1 to know more
about .NET Core 2.1. Where, ASP.NET Core 2.1 introduces supports
for SignalR, HTTPS by default, introduction of HttpClientFactory and
many other. Read Quick summary of what’s new in ASP.NET Core
2.1. Also read the migration guide to migrate ASP.NET Core 2.0 app
to 2.1.
Q.What are the differences between ASP.NET MVC 5 and ASP.NET
MVC Core 1.0?
Ans: Read Difference between ASP.NET MVC 5 and ASP.NET MVC
Core 1.0.
In ASP.NET Core 6, you can skip middleware by conditionally executing it based on certain
criteria, similar to earlier versions. Here are some effective ways to do this:
1. Using Conditional Logic in Middleware
You can check conditions directly within your middleware to decide whether to execute the
rest of the pipeline:
csharp
Copy code
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Check some condition to decide whether to skip
if (context.Request.Path.StartsWithSegments("/skip"))
{
await _next(context); // Skip further processing
return;
}
// Your middleware logic here
await _next(context); // Call the next middleware
}
}
// In Program.cs (for .NET 6)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<MyMiddleware>();
// Other middlewares...
app.Run();
2. Using UseWhen for Conditional Middleware
You can use app.UseWhen to apply middleware only under certain conditions:
csharp
Copy code
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"),
appBuilder =>
{
appBuilder.UseMiddleware<MyMiddleware>();
});
3. Using Middleware Extensions
Create an extension method that accepts a predicate to determine whether to execute the
middleware:
csharp
Copy code
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseConditionalMiddleware(this
IApplicationBuilder builder, Func<HttpContext, bool> predicate)
{
return builder.Use(async (context, next) =>
{
if (!predicate(context))
{
await next();
return;
}
// Your middleware logic here
await next();
});
}
}
// In Program.cs
app.UseConditionalMiddleware(context => !
context.Request.Path.StartsWithSegments("/skip"));
// Other middlewares...
4. Using Endpoint Routing
With endpoint routing, you can also configure middleware to run only for specific endpoints,
which can help you control middleware execution based on route matching.
Conclusion
By employing these methods, you can effectively manage middleware execution in ASP.NET
Core 6. Choose the approach that best aligns with your application's architecture and
requirements.
4o mini