2/Sep/2024 | 20 minutes to read
dotnet
Here is a List of essential ASP.NET Core Interview Questions and Answers for Freshers and mid level of Experienced Professionals. All answers for these ASP.NET Core questions are explained in a simple and easiest way. These basic, advanced and latest ASP.NET Core questions will help you to clear your next Job interview.
These interview questions are targeted for ASP.NET Core, ASP.NET Core MVC and Web API. You must know the answers of these ASP.NET Core interview questions to clear a .NET FullStack developer interview. C# Programming language is used to show examples.
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, fast, secure and cloud enabled applications. With ASP.NET Core you can
2. Does .NET Hot reload support for ASP.NET Core?
.NET Hot Reload is available for ASP.NET Core 6.0 and later versions applications. It applies the code changes, including
stylesheet changes to an app that is already running without losing app state and restarting the app.
Not all code changes trigger browser refresh
like startup middleware changes unless it's not an inline middleware, configured services, removing component parameter attribute in Razor etc.
For more refer Hot Reload in ASP.NET Core.
3. What are the benefits of using ASP.NET Core over ASP.NET?
ASP.NET Core comes with the following benefits over ASP.NET.
4. What is the role of Startup class?
Startup class is responsible for configuration related things as below.
Program.cs
file contains all startup code.
// 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. 5. 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.
6. 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
7. Explain the request pipeline or middleware pipeline in ASP.NET Core.
A request pipeline or middleware pipeline consists of a sequence of request delegates which are called one after another to perform operations before and after the next delegate. For more about request processing pipeline for ASP.NET MVC visit Request Processing Pipeline.
8. What do you understand by short-circuiting the request pipeline in ASP.NET Core.
Generally, one delegate passes the request to the next delegate to perform some operations but when a delegate does not pass the request to the next delegate then it's known as short-circuiting the request pipeline. You can short-circuit the request pipeline by not using the 'next' parameter. Short-circuiting Request Pipeline in ASP.NET Core.
9. Explain the difference between app.Run
and app.Use
in ASP.NET Core.
app.Use((context, nextMidWare) => { context.Response.Body.Write("Hello app.Use"); nextMidWare(context);});
app.Run((context) => context.Response.Body.Write("Hello app.Run"));
app.Use((context, nextMidWare) => context.Response.Body.Write("Hello , again app.Use"));
Output:
Hello app.Use
Hello app.Run
10. What problems does Dependency Injection solve?
Public class A {
MyDependency dep = new MyDependency();
public void Test(){
dep.SomeMethod();
}
}
But these direct dependencies can be problematic for the following reasons.
11. Describe the Service Lifetimes.
When Services are registered, there is a lifetime for every service. ASP.NET Core provides the following lifetimes.
12. Explain the Middleware in ASP.NET Core.
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.
13. 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.
14. 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:
15. Describe the Generic Host and Web Host.
// 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:
13. How Configuration works in ASP.NET Core?
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.
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
17. How Logging works in .NET Core and ASP.NET Core?
By default, ASP.NET Core provides below logging providers as a part of WebApplication.CreateBuilder
code in program.cs class.
ILogger
instance
using Dependency Injection.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?
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.
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
// 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.
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.
25. How does Model Binding work in ASP.NET Core?
Model binding provides the capability to map the data from HTTP requests to action method parameters in your controller. It simplifies handling incoming data by automatically converting it from various sources such as JSON, form values, query strings, route data etc., into .NET objects. Model binding helps in reducing manual parsing of data and binding that data to .NET types. Model binding happens after the routing system selects the action method. For more you can refer Model Binding in ASP.NET Core.
25. Explain Custom Model Binding.
26. Describe Model Validation.
Model Validation in ASP.NET Core is the process of ensuring that the data submitted by the user meets certain rules and constraints before processing it further. It helps to maintain data integrity and prevent invalid or malicious data from being processed by the application.
ASP.NET Core provides built-in support for model validation using data annotations. These annotations are applied to the properties of the model class, and they define the validation rules that should be enforced. For example, the [Required] attribute specifies that a property must have a non-null value, and the [StringLength] attribute sets the minimum and maximum length for a string property.
When a request is made, ASP.NET Core automatically validates the model based on the defined validation rules. If any validation errors occur, they are added to the ModelState object, which can be accessed and displayed to the user.
27. How to write custom ASP.NET Core middleware?
public class RequestPathLoggerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public RequestPathLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger();
}
public async Task InvokeAsync(HttpContext context)
{
_logger.LogInformation($"Request path: {context.Request.Path}");
await _next(context);
}
}
After creating the middleware class, you need to register it in the Startup.cs file by calling the UseMiddleware extension method in the Configure method:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Other middleware registrations...
app.UseMiddleware();
// Other middleware registrations...
}
This way, your custom middleware will be executed for every request in the specified order within the request pipeline.
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.
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.
For more visit Caching in ASP.NET Core.
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.
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?
@Html.AntiForgeryToken()
and then you can validate it in controller by ValidateAntiForgeryToken()
method.38. How to prevent Cross-Site Scripting (XSS) in ASP.NET Core?
39. How to enable Cross-Origin Requests (CORS) in ASP.NET Core?
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.
OnResourceExecuting
filter runs the code before rest of filter pipeline and OnResourceExecuted
runs the code after rest of filter pipeline.
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.
44. How does bundling and minification work in ASP.NET Core?
For more visit Bundling and Minification.
44. How will you improve performance of ASP.NET Core Application?
For more visit Performance Best Practices.
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.
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.
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. 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 IEnumerableGetOrdersByCustomer(int customerId) { ... } . . . [Route("customers/{customerId}/orders/orderId")] public IEnumerable GetOrdersByCustomer(int customerId, int orderId) { ... }
6. Explain dependency injection for controllers.
ConfigureServices
method. You can add services as constructor parameters, ASP.NET Core runtime
will resolve these dependencies from the service container.
7. How ASP.NET Core supports dependency injection into views?
8. How will you unit test a controller?
9. What is Cache Tag Helper in ASP.NET Core MVC?
10. How validation works in MVC and how they follow DRY Pattern?
11. Describe the complete request processing pipeline for ASP.NET Core MVC.
1. How much will you rate yourself in ASP.NET Core?
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. The interviewer expects a realistic self-evaluation aligned with your qualifications.
2. What challenges did you face while working on ASP.NET Core?
The challenges faced while working on ASP.NET Core projects are highly dependent on one's specific work experience and the technology involved. You should explain any relevant challenges you encountered related to ASP.NET Core during your previous projects.
3. What was your role in the last Project related to ASP.NET Core?
This question is commonly asked in interviews to understand your specific responsibilities and the functionalities you implemented using ASP.NET Core in your previous projects. Your answer should highlight your role, the tasks you were assigned, and the ASP.NET Core features or techniques you utilized to accomplish those tasks.
4. How much experience do you have in ASP.NET Core?
Here you can tell about your overall work experience on ASP.NET Core.
5. Have you done any ASP.NET Core Certification or Training?
Whether a candidate has completed any ASP.NET Core certification or training is optional. While certifications and training are not essential requirements, they can be advantageous to have.
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 info@qfles.com. 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.