Core
Core
Core
All Interviews
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.
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 classes are used.
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
For more about request processing pipeline for ASP.NET MVC visit Request Processing
Pipeline.
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();
When Services are registered, there is a lifetime for every service. ASP.NET Core
provides the 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.
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.
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:
The host setup the server, request pipeline and responsible for app startup and lifetime
management. There are two hosts:
.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();
}
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.
14. How to read values from Appsettings.json file?
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.
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.
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
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
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
Yes, you can run an ASP.NET application or .NET Core application in Docker
containers.
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.
37. What is XSRF or CSRF? How to prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in
ASP.NET Core?
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.
44. Explain Buffering and Streaming approaches to upload files in ASP.NET Core.
44. What tools have you used for diagnosing performance issues in ASP.NET Core Application?
Visual Studio comes with default profiling and diagnostics tools, which you can use at
development time from the visual studio. These are the built-in tools and allow the
analysis of memory usage, CPU usage and performance events in ASP.NET Core
applications.
For more visit Performance Diagnostic Tools.
ASP.NET Core MVC Interview Questions
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.
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.
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) { ... }
Dependency Injection is a design pattern used to inject the object dependencies inside
controllers. ASP.NET core supports built-in dependency injection, just you need to
register those services in the startup file inside ConfigureServices method. You can add
services as constructor parameters, ASP.NET Core runtime will resolve these
dependencies from the service container.
You can perform dependency injection in two ways.
Constructor Injection
Action Injection using FromServices attribute.
You can access additional settings by using options pattern instead of directly
injecting IConfiguration inside the controller.
12. How validation works in MVC and how they follow DRY Pattern?
13. Describe the complete request processing pipeline for ASP.NET Core MVC.
When you attend an interview, Interviewer may ask you to rate yourself in a specific
Technology like ASP.NET Core, So It's depend on your knowledge and work experience
in ASP.NET Core.
This question may be specific to your technology and completely depends on your past
work experience. So you need to just explain the challenges you faced related to
ASP.NET Core in your Project.
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.
Here you can tell about your overall work experience on ASP.NET Core.
It depends on the candidate whether you have done any ASP.NET Core training or
certification. Certifications or training are not essential but good to have.
Conclusion