asp.net core interview questions and answers for fresher and experienced.
Some ASP.NET Core interview questions along with brief explanations.
1. What is ASP.NET Core?
Answer:
ASP.NET Core is a cross-platform, high-performance framework for building modern, cloud-based, and internet-connected applications. It is an open-source framework developed by Microsoft, used to build web applications and APIs. Unlike the traditional ASP.NET framework, ASP.NET Core can run on Windows, macOS, and Linux.
2. Explain the difference between ASP.NET and ASP.NET Core?
Answer:
ASP.NET: Framework for building web applications, supports only Windows.
ASP.NET Core: Cross-platform, supports Windows, macOS, and Linux, offers better performance, modular architecture, and has built-in dependency injection.
3. What are the benefits of using ASP.NET Core?
Answer:
Cross-platform: Runs on Windows, macOS, and Linux.
High performance: Faster than traditional ASP.NET.
Modular: Allows only required modules to be included, reducing application size.
Dependency injection: Built-in dependency injection for better management of dependencies.
Unified programming model: For building web UI and APIs.
4. What is Middleware in ASP.NET Core?
Answer:
Middleware is software that is assembled into an application pipeline to handle requests and responses. Each component in the pipeline can either handle a request directly or pass it to the next component. Common examples of middleware include authentication, routing, and error handling.
5. How does dependency injection work in ASP.NET Core?
Answer:
Dependency Injection (DI) is built into ASP.NET Core. It allows you to register services in the Startup.cs file (via ConfigureServices method) and inject them into controllers or other services. This leads to better testing, maintenance, and scalability by promoting loosely coupled code.
6. What is Kestrel in ASP.NET Core?
Answer:
Kestrel is a cross-platform web server used as the default web server in ASP.NET Core. It is lightweight and provides high-performance HTTP server capabilities.
7. What are Razor Pages in ASP.NET Core?
Answer:
Razor Pages is a new feature in ASP.NET Core that simplifies web application development by introducing a page-focused approach. Each page in Razor Pages is backed by a .cshtml file (UI) and a corresponding PageModel class (logic), offering a more organized structure compared to MVC.
8. Explain the Startup.cs file in ASP.NET Core.
Answer:
The Startup.cs file is the entry point for configuring services and middleware in an ASP.NET Core application. It contains two main methods.
ConfigureServices: Used to register services like logging, dependency injection, etc.
Configure: Defines how the application responds to HTTP requests using middleware.
9. What is the difference between IActionResult and ActionResult in ASP.NET Core?
Answer:
IActionResult: It is an interface that allows for more flexibility, as any result type can implement it.
ActionResult: A base class that provides predefined result types (e.g., Ok(), NotFound()), more specific to MVC.
10. What is the purpose of the appsettings.json file in ASP.NET Core?
Answer:
appsettings.json is a configuration file used to store application settings like database connection strings, logging settings, and other custom configurations. It supports hierarchical settings and environment-specific settings through appsettings.Development.json or other environment-based files.
11. What is Model Binding in ASP.NET Core?
Answer:
Model Binding in ASP.NET Core is the process of converting data (from query strings, form inputs, or route data) into .NET objects. This simplifies working with HTTP request data as it directly binds data to controller action parameters.
12. What is Tag Helpers in ASP.NET Core?
Answer:
Tag Helpers are a feature in ASP.NET Core that allow server-side code to participate in creating and rendering HTML elements. They provide a way to interact with the HTML elements in Razor views while maintaining the simplicity and readability of HTML.
13. What is the difference between AddScoped, AddTransient, and AddSingleton in ASP.NET Core?
Answer:
AddScoped: Creates a new instance of the service per request.
AddTransient: Creates a new instance of the service every time it is requested.
AddSingleton: Creates a single instance of the service for the lifetime of the application.
14. What is Entity Framework Core (EF Core)?
Answer:
EF Core is an ORM (Object Relational Mapper) for .NET Core applications. It allows developers to interact with a database using .NET objects, eliminating the need for most of the SQL code. It supports LINQ queries, change tracking, schema migrations, and more.
15. How is routing handled in ASP.NET Core?
Answer:
Routing in ASP.NET Core defines how URLs map to actions in a controller or Razor Pages. Routes can be defined in the Startup.cs file using app.UseRouting() and app.UseEndpoints(). Attribute-based routing can also be used directly on controllers and actions by decorating them with route attributes.
16. What is the difference between synchronous and asynchronous actions in ASP.NET Core?
Answer:
Synchronous actions block the current thread until the operation completes, which can reduce the application's scalability, especially under heavy load.
Asynchronous actions free up the thread to handle other requests while the operation is in progress. This is achieved using async and await keywords, which allows ASP.NET Core to handle more requests concurrently, improving performance and scalability.
17. What are Filters in ASP.NET Core?
Answer:
Filters in ASP.NET Core are used to run code before or after certain stages in the request processing pipeline. They can be used to handle cross-cutting concerns such as logging, authorization, exception handling, and caching. Common filter types are:
Authorization filters
Resource filters
Action filters
Exception filters
Result filters
18. Explain ViewModel in ASP.NET Core MVC.
Answer:
A ViewModel is a class that contains data passed from the controller to the view. It helps to shape the data to fit the view's requirements, often combining multiple models or adding additional properties that are not present in the original domain model.
19. What is the use of IHostedService in ASP.NET Core?
Answer:
IHostedService is an interface in ASP.NET Core used to create background tasks or long-running services that can be run alongside the web application. Implementing this interface allows services to be started when the application starts and stopped when the application stops.
20. What is CORS in ASP.NET Core?
Answer:
CORS (Cross-Origin Resource Sharing) is a security feature implemented in browsers to prevent unauthorized requests to other domains. ASP.NET Core provides middleware to configure CORS policies, allowing or restricting cross-origin requests. This can be configured in Startup.cs using UseCors() and is particularly useful when dealing with APIs.
21. How do you handle exceptions in ASP.NET Core?
Answer:
ASP.NET Core provides several ways to handle exceptions:
Exception Filters: Custom exception filters can catch exceptions thrown in controller actions.
Middleware: Use the built-in middleware app.UseExceptionHandler() to centralize error handling.
Logging: Exceptions can also be logged to external sources like files or monitoring tools via dependency injection in Startup.cs.
22. What is the difference between Web API and MVC in ASP.NET Core?
Answer:
MVC (Model-View-Controller): Primarily used for web applications that generate HTML views to be rendered in a browser. It supports both views and API-based responses (JSON/XML).
Web API: Focused on building RESTful services, it does not return views but rather data (JSON or XML) for client applications.
23. Explain the role of IConfiguration in ASP.NET Core.
Answer:
IConfiguration is used to read configuration settings in ASP.NET Core applications. It can be configured to read from multiple sources such as:
appsettings.json
Environment variables
Command-line arguments
Azure Key Vault, and more. It allows for strongly-typed configurations using classes mapped to configuration sections.
24. What is Endpoint Routing in ASP.NET Core?
Answer:
Endpoint Routing is a system that routes HTTP requests to the appropriate endpoint in ASP.NET Core. It enables centralized control of routes and allows middleware to access routing information. This approach simplifies things like route-based authorization and diagnostics.
25. What is Health Checks in ASP.NET Core?
Answer:
Health Checks are used to monitor the status of an application, ensuring that it is running as expected. ASP.NET Core includes built-in middleware for defining and reporting health checks, allowing developers to monitor things like database connectivity, disk space, or third-party service availability.
26. What is the UseRouting() and UseEndpoints() middleware in ASP.NET Core?
Answer:
UseRouting(): This middleware sets up routing in the request pipeline and matches the incoming HTTP request to a route.
UseEndpoints(): After routing, this middleware executes the matched endpoint, such as an MVC action or Razor Page.
27. What are Areas in ASP.NET Core?
Answer:
Areas are used in ASP.NET Core MVC to group related controllers and views into a folder structure. This helps in organizing large applications into smaller functional segments, making it easier to manage and scale.
28. What is Dependency Injection (DI) and how is it implemented in ASP.NET Core?
Answer:
Dependency Injection is a design pattern used to inject dependencies (objects/services) into a class rather than creating them internally. In ASP.NET Core, DI is built into the framework. It is configured in the Startup.cs file in the ConfigureServices method, where services are registered with the DI container using methods like AddScoped(), AddTransient(), and AddSingleton().
29. What is WebHost in ASP.NET Core?
Answer:
The WebHost is the component that configures and launches the ASP.NET Core application. It sets up the server (Kestrel, IIS, etc.), configures the request pipeline, and manages services. The CreateHostBuilder() method in the Program.cs file is where the WebHost is configured.
30. What is SignalR in ASP.NET Core?
Answer:
SignalR is a library in ASP.NET Core used for real-time web functionality. It enables server-side code to push content to connected clients instantly, rather than waiting for the client to request updates. It is typically used for chat applications, live dashboards, or notifications.
31. What is the purpose of UseStaticFiles() middleware in ASP.NET Core?
Answer:
UseStaticFiles() middleware is used to serve static files like HTML, CSS, JavaScript, images, and other assets in an ASP.NET Core application. By default, it serves files from the wwwroot folder, but custom paths can also be configured.
32. What is the role of IApplicationBuilder in ASP.NET Core?
Answer:
IApplicationBuilder is used to configure the HTTP request pipeline by specifying the middleware that will handle the requests. It's used in the Configure() method of the Startup.cs file to add middleware components like authentication, logging, error handling, routing, etc.
33. How does Model Validation work in ASP.NET Core?
Answer:
Model validation in ASP.NET Core ensures that the data received from user input meets certain criteria before it is processed. It uses attributes like [Required], [StringLength], [Range], and custom validation attributes to validate properties of models. ASP.NET Core automatically checks for these validations and returns validation errors if any are found.
34. What is gRPC, and how is it supported in ASP.NET Core?
Answer:
gRPC is a high-performance, cross-platform framework for remote procedure calls (RPC). ASP.NET Core supports gRPC for building efficient, strongly-typed APIs. It uses HTTP/2 and protocol buffers to serialize data, making it faster than JSON-based REST APIs. gRPC services can be configured in the Startup.cs using app.UseGrpc().
35. How does Blazor fit into the ASP.NET Core ecosystem?
Answer:
Blazor is a web framework that allows developers to build interactive web applications using C# instead of JavaScript. Blazor comes in two hosting models:
Blazor Server: Runs on the server and communicates with the client via SignalR.
Blazor WebAssembly: Runs directly in the browser using WebAssembly. Blazor integrates seamlessly with ASP.NET Core, offering a full-stack C# development experience.
36. What is Output Caching in ASP.NET Core?
Answer:
Output Caching in ASP.NET Core stores the output of a controller action or Razor Page in memory, which reduces the number of times the same result needs to be generated. This improves performance by returning cached responses for similar requests. The ResponseCache attribute is used to configure caching.
37. How does ASP.NET Core handle request pipeline customization?
Answer:
ASP.NET Core allows complete customization of the request pipeline via middleware components. In the Startup.cs file, developers can specify the sequence of middleware using methods like app.UseRouting(), app.UseAuthentication(), app.UseAuthorization(), etc. Middleware are executed in the order they are added, allowing for fine-grained control over request handling.
38. What is HSTS in ASP.NET Core, and why is it used?
Answer:
HSTS (HTTP Strict Transport Security) is a web security policy mechanism that helps protect websites against man-in-the-middle attacks by enforcing secure (HTTPS) connections. ASP.NET Core provides built-in support for HSTS through the UseHsts() middleware, which ensures that browsers only interact with the app using HTTPS.
39. What is WebSocket and how is it supported in ASP.NET Core?
Answer:
WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection. ASP.NET Core supports WebSocket, allowing real-time communication between client and server. It is often used in applications like chat systems, live notifications, and multiplayer games.
40. What is IWebHostBuilder and how does it differ from IHostBuilder?
Answer:
IWebHostBuilder is used for configuring and launching ASP.NET Core web applications. It includes web-specific functionalities like setting up the Kestrel server, IIS integration, and routing middleware.
IHostBuilder is a more generalized builder used for configuring any .NET Core application (including ASP.NET Core). It supports background services and worker services, in addition to web applications.
41. What are View Components in ASP.NET Core?
Answer:
View Components are reusable components in ASP.NET Core that allow you to embed dynamic, logic-driven content in views, similar to partial views but with enhanced capabilities. Unlike controllers, View Components do not handle requests directly; they are invoked from views and return HTML to be rendered.
42. How do you configure logging in ASP.NET Core?
Answer:
Logging in ASP.NET Core can be configured through the Logging section in appsettings.json, or programmatically in Startup.cs. ASP.NET Core supports multiple logging providers, such as Console, Debug, EventLog, and third-party providers like Serilog and NLog. The ILogger interface is used to log messages in different categories (e.g., Information, Error, Warning).
43. What is the UseAuthorization() middleware, and how does it differ from UseAuthentication()?
Answer:
UseAuthentication(): Adds the authentication middleware to the request pipeline, which checks if the user is authenticated.
UseAuthorization(): This middleware ensures that after a user is authenticated, they have the correct permissions (or roles) to access a particular resource or action.
44. What is Dependency Inversion Principle, and how does ASP.NET Core adhere to it?
Answer:
The Dependency Inversion Principle is one of the SOLID principles that states that high-level modules should not depend on low-level modules, but both should depend on abstractions. ASP.NET Core follows this principle by using dependency injection (DI), where dependencies are injected through interfaces, promoting loose coupling and better testability.
45. What are Data Protection APIs in ASP.NET Core?
Answer:
Data Protection APIs provide a simple, secure way to encrypt and decrypt sensitive data in ASP.NET Core applications. It is used for tasks like encrypting authentication cookies, managing user tokens, or securing sensitive configuration data. The APIs offer encryption, key management, and automatic key rotation.
46. What is the difference between Map() and MapWhen() in ASP.NET Core?
Answer:
Map(): Maps a middleware pipeline to a specific request path, meaning all requests matching that path will be handled by the pipeline defined inside the Map() method.
MapWhen(): Provides more flexibility by allowing you to map middleware based on a condition (typically a lambda function), not just a specific path.
47. What is the Razor Class Library (RCL) in ASP.NET Core?
Answer:
A Razor Class Library (RCL) is a project type that allows developers to create reusable Razor components (e.g., views, Razor Pages, static assets) and share them across multiple ASP.NET Core projects. RCLs are ideal for building reusable UI libraries or components like themes or shared layouts.
48. What is Endpoint Metadata in ASP.NET Core?
Answer:
Endpoint Metadata provides a way to store information about an endpoint in ASP.NET Core routing, such as which HTTP methods are supported, or specific policies like authentication and authorization requirements. Metadata is attached to the endpoint and can be accessed programmatically for making routing decisions.
49. How is session management handled in ASP.NET Core?
Answer:
ASP.NET Core provides middleware for managing user sessions. Sessions are stored on the server, and a session ID is sent to the client via a cookie. Data can be stored in the session using the ISession interface, and the session's lifetime can be configured via services.AddSession() in the Startup.cs file.
50. What is the role of IActionFilter in ASP.NET Core?
Answer:
IActionFilter is an interface used to define filters that run before and after the execution of an action method. This allows developers to perform tasks such as logging, modifying action parameters, or handling exceptions. The OnActionExecuting() method runs before the action method is executed, and OnActionExecuted() runs after.
No comments:
Post a Comment