61 Essential ASP - NET Core Interview Questions and Answers
61 Essential ASP - NET Core Interview Questions and Answers
61 Essential ASP - NET Core Interview Questions and Answers
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.
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.
Configuration = configuration;
services.AddRazorPages();
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Error");
app.UseHsts();
app.UseHttpsRedirection();
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.
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.
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 {
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.
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.
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.
.NET Generic Host is recommended and ASP.NET Core template builds a .NET Generic Host on app startup.
// Host creation
CreateWebHostBuilder(args).Build().Run();
WebHost.CreateDefaultBuilder(args)
.UseStartup();
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.
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.
class Test{
Configuration = configuration;
Default configuration provider first load the values from appsettings.json and then from appsettings.Environment.json file.
You can also read the appsettings.json values using options pattern described
Read values from appsettings.json file.
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.
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. For more visit
How to use multiple environments in
ASP.NET Core
app.UseEndpoints(endpoints =>
});
});
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.
await next();
if (context.Response.StatusCode == 404)
context.Request.Path = "/not-found";
await next();
context.Request.Path = "/Home/Error";
await next();
});
You can serve files outside of this webroot folder by configuring Static File Middleware as following.
app.UseStaticFiles(new StaticFileOptions
});
Cookies
Session State
TempData
Query strings
Hidden fields
HttpContext.Items
Cache
Response caching headers control the response caching. ResponseCache attribute sets these caching headers with additional
properties.
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.
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.
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)
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.
44. Explain Buffering and Streaming approaches to upload files in ASP.NET Core.
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{
Class Book{
This Author and Book data can be passed to view by creating Author ViewModel inside controller.
[Route("customers/{customerId}/orders/orderId")]
12. How validation works in MVC and how they follow DRY Pattern?
13. Describe the complete request processing pipeline for ASP.NET Core MVC.
3. What was your role in the last Project related to ASP.NET Core?
It's based on your role and responsibilities assigned to you and what functionality you implemented using ASP.NET Core in your
project. This question is generally
asked in every interview.
Conclusion
We have covered some frequently asked ASP.NET Core Interview Questions and Answers to help you for your Interview. All these
Essential ASP.NET Core Interview Questions are targeted for mid level of experienced Professionals and freshers.
While attending any ASP.NET Core Interview if you face any difficulty to answer any question please write to us at [email protected].
Our IT Expert team will find the best answer and will update on the portal. In case we find any new ASP.NET Core questions, we will
update the same here.
LATEST LEGAL
Vue.js
Azure DevOps
NoSQL DB
Cloud Computing