0% found this document useful (0 votes)
29 views38 pages

Core Detailed Q&A

.NET Core is a cross-platform, high-performance framework for building modern applications, evolving into .NET 5/6/7/8. Key differences between .NET Framework and .NET Core include cross-platform support, performance, and deployment methods. The document covers various aspects of .NET Core including CLI, middleware, dependency injection, routing, and configuration management.

Uploaded by

Shrikant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views38 pages

Core Detailed Q&A

.NET Core is a cross-platform, high-performance framework for building modern applications, evolving into .NET 5/6/7/8. Key differences between .NET Framework and .NET Core include cross-platform support, performance, and deployment methods. The document covers various aspects of .NET Core including CLI, middleware, dependency injection, routing, and configuration management.

Uploaded by

Shrikant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

NET Core – Questions

1. What is .NET Core?


Answer:
.NET Core is a cross-platform, high-performance, open-source framework developed by
Microsoft for building modern, cloud-based, internet-connected applications.
Key features:

 Cross-platform (Windows, Linux, macOS)


 CLI support
 Modular and lightweight
 Improved performance
 Supports microservices and containers
It has now evolved into .NET 5/6/7/8, which unify .NET Core and .NET Framework.

2. What are the differences between .NET Framework and .NET Core?
Answer:

Feature .NET Framework .NET Core (.NET 5+)


Platform Windows only Cross-platform (Win/Linux/macOS)
Application Models Web Forms, WPF, etc. ASP.NET Core, Blazor, etc.
Performance Moderate High
Deployment Global Assembly Cache Self-contained or framework-dependent
Open Source Partially Fully Open Source

3. What is the .NET Core CLI?


Answer:
The .NET Core Command Line Interface (CLI) is a cross-platform toolchain for developing,
building, running, and publishing .NET Core applications from the command line.
Examples:

 dotnet new – Creates a new project


 dotnet build – Builds the project
 dotnet run – Runs the app
 dotnet publish – Prepares for deployment
4. What is the role of the Program.cs and Startup.cs files in an ASP.NET Core
application?
Answer:

 Program.cs: Defines the entry point of the application and hosts the web server using the
Generic Host (CreateHostBuilder)
 Startup.cs: Contains ConfigureServices() to register services, and Configure() to
define the request pipeline (middlewares like routing, authentication, etc.)

5. What is dependency injection (DI) in .NET Core?


Answer:
DI is a design pattern where a class's dependencies are provided externally rather than
instantiated inside the class.

This promotes loose coupling, easier testing, and better maintenance.

6. What are middleware components in ASP.NET Core?


Answer:
Middleware are software components that form a pipeline to handle requests and responses.
Each component can:

 Process incoming request


 Call the next middleware using await next()
 Process outgoing response

Common middleware: Routing, Authentication, Static Files, etc.


7. What is Kestrel in .NET Core?
Answer:
Kestrel is the cross-platform web server used by ASP.NET Core. It is:

 Lightweight and fast


 Designed for handling HTTP requests
 Runs behind IIS (on Windows) or Nginx/Apache (on Linux) for reverse proxy scenarios
 Suitable for development and production

8. What is the difference between AddSingleton(), AddScoped(), and AddTransient()?


Answer:

Lifetime Description
Singleton One instance for the entire app lifetime
Scoped One instance per request
Transient New instance every time it is requested/injected

 Choose based on desired lifespan of the object.

9. What is Model Binding in ASP.NET Core?


Answer:
Model binding automatically maps data from HTTP requests (query string, form data, route data,
etc.) to parameters in action methods or to model properties.

Here, user gets automatically bound to posted form data.


10. What is the appsettings.json file used for?
Answer:
It is used for storing configuration settings like connection strings, app-specific options, and
environment-based settings.

11. How is configuration handled in .NET Core?


Answer:
.NET Core supports configuration through:

 appsettings.json
 appsettings.{Environment}.json
 Environment variables
 Command-line arguments
It uses IConfiguration and IOptions<T> interfaces for access and binding to strongly
typed classes.

12. What is the use of IConfiguration and IOptions<T>?


Answer:

 IConfiguration: Used to read configuration values


 IOptions<T>: Binds configuration to strongly-typed classes
13. What is routing in ASP.NET Core?
Answer:
Routing maps incoming HTTP requests to the appropriate controller actions. ASP.NET Core
uses both conventional and attribute routing.

Conventional routing example in Startup.cs:

14. What is Attribute Routing in ASP.NET Core?


Answer:
Allows defining routes using attributes directly on controller and action methods:

More flexible and readable for APIs.


15. What is Entity Framework Core (EF Core)?
Answer:
EF Core is the ORM (Object Relational Mapper) for .NET Core.
It allows:

 Querying and saving data using LINQ


 Code-first, database-first, or hybrid approaches
 Supports migrations for schema changes

16. What is a migration in EF Core?


Answer:
Migrations are a way to apply incremental schema changes to the database using code.

Commands:

 Add-Migration InitialCreate
 Update-Database
 Remove-Migration

They track model changes and generate SQL automatically.

17. What are filters in ASP.NET Core?


Answer:
Filters run before or after actions and can be used for logging, authorization, exception handling,
etc.
Types:

 Authorization filters
 Resource filters
 Action filters
 Result filters
 Exception filters
18. What is middleware vs filter in ASP.NET Core?
Answer:

 Middleware: Works globally in the request pipeline (at app level)


 Filters: Work at the controller/action level and allow finer-grained behavior

Filters are MVC-specific; middleware is framework-wide.

19. How is logging handled in ASP.NET Core?


Answer:
.NET Core uses built-in logging via ILogger<T>, supporting providers like Console, Debug,
Azure, and Serilog.

Logging is configured in Program.cs or appsettings.json.

20. What is the difference between IApplicationBuilder and IServiceCollection?


Answer:

Interface Purpose
IApplicationBuilder Used in Configure() to build request pipeline (middlewares)
IServiceCollection
Used in ConfigureServices() to register dependencies and services for
DI

21. What is the difference between synchronous and asynchronous programming in .NET
Core?
Answer:

 Synchronous code blocks execution until the operation completes.


 Asynchronous code uses async/await with Task, allowing the app to continue working
while waiting for I/O-bound operations (like DB or API calls) to complete.

Async improves scalability and responsiveness, especially in web applications.


22. How do you implement global exception handling in ASP.NET Core?
Answer:
There are several ways:

1. Use UseExceptionHandler middleware:

3. Exception Filters for controller-specific error handling.

23. What is the difference between IHostedService and BackgroundService?


Answer:

 IHostedService: Interface for creating long-running tasks like scheduled jobs or event
listeners.
 BackgroundService: An abstract class that implements IHostedService, simplifies
background task implementation using ExecuteAsync.
24. What is the difference between WebHost and Generic Host in .NET Core?
Answer:

 WebHost (used in .NET Core 2.x): Tailored for web apps only.
 Generic Host (from .NET Core 3.0+): A unified model for hosting web apps,
background services, or other workloads.

Generic Host is now the standard for all .NET apps.

25. How do you implement logging using third-party providers like Serilog or NLog
in .NET Core?
Answer:

1. Install NuGet package (e.g., Serilog.AspNetCore).

2. Configure in Program.cs:
3. Use DI:

26. What are Tag Helpers in ASP.NET Core?


Answer:
Tag Helpers are server-side components that enable C# code in Razor views using HTML-like
syntax.

Example:

27. How does model validation work in ASP.NET Core?


Answer:
Use data annotations like [Required], [Range], [EmailAddress] in models.
ASP.NET Core automatically validates model state before the action runs:
28. What is the role of UseRouting() and UseEndpoints() in .NET Core?
Answer:

 UseRouting() enables routing capabilities (middleware that matches the route).


 UseEndpoints() maps the route to actual controllers or endpoints.

Order matters:

29. What is CORS and how do you enable it in ASP.NET Core?


Answer:
CORS (Cross-Origin Resource Sharing) allows your server to accept requests from other
domains.

In Startup.cs:

Used in APIs to enable frontend-backend communication hosted on different origins.

30. What is the purpose of the MapControllers() method?


Answer:
MapControllers() maps attribute-routed controllers to the request pipeline.
It activates [Route]-decorated controller actions. Required when using [ApiController] or
[Route] attributes.
31. What is the [ApiController] attribute in ASP.NET Core?
Answer:

 Introduced in ASP.NET Core 2.1


 Simplifies model validation and binding for Web APIs
 Enables automatic 400 responses for model validation errors
 Assumes attribute routing

32. How is session state handled in ASP.NET Core?


Answer:
Sessions are disabled by default. To enable:

Then use HttpContext.Session.SetString() and .GetString() to store and retrieve session


data.

33. How do you secure Web APIs in .NET Core?


Answer:
Options include:

 JWT (JSON Web Token) authentication


 OAuth2/OpenID Connect (e.g., with IdentityServer)
 API Keys
 HTTPS
 Role-based authorization ([Authorize(Roles = "Admin")])

34. What is the IHttpClientFactory and why should you use it?
Answer:
A factory introduced in .NET Core 2.1 to manage HttpClient lifetimes, avoiding socket
exhaustion issues.
Used with Typed, Named, or Generated clients.

35. What are gRPC services in .NET Core?


Answer:

 High-performance, contract-first, binary RPC protocol


 Ideal for microservices or internal APIs
 Faster than REST for inter-service communication

Configured in ASP.NET Core using .proto files and Grpc.AspNetCore.

36. What is Blazor in .NET Core?


Answer:
Blazor is a framework for building interactive web UIs using C# instead of JavaScript.
Types:

 Blazor Server (runs on server via SignalR)


 Blazor WebAssembly (runs in browser via WASM)

Blazor promotes full-stack .NET development in web apps.

37. What is app.UseStaticFiles() in ASP.NET Core?


Answer:
This middleware enables serving static files like HTML, CSS, JS, and images from the wwwroot
folder.

Must be placed before routing in the pipeline.


38. What is a Razor Page?
Answer:
A page-based programming model in ASP.NET Core, introduced in 2.0.
More structured than MVC for simple scenarios.
Each page has a .cshtml and .cshtml.cs file for markup and logic.

39. How do you create a custom middleware in ASP.NET Core?


Answer:
Custom middleware handles request/response logic.

Register in pipeline using app.UseMiddleware<MyMiddleware>();.

40. What is endpoint routing?


Answer:
Endpoint routing separates routing logic from execution. Introduced in ASP.NET Core 3.x.

It enables matching routes first, then executing handlers (e.g., controller actions, Razor pages,
gRPC endpoints).

41. What is SignalR in ASP.NET Core?


Answer:
SignalR is a real-time communication library that allows server-side code to push content to
connected clients instantly.

Features:

 Supports WebSockets, Server-Sent Events, Long Polling (auto-negotiated)


 Ideal for chat apps, live dashboards, real-time notifications
 Uses hubs to send/receive messages

Example usage:

42. What are launchSettings.json and its purpose?


Answer:
This file in the Properties folder defines environment-specific settings for local development.

Includes:

 Environment variables (ASPNETCORE_ENVIRONMENT)


 Application URLs
 Hosting profiles for IIS Express, Kestrel, Docker
43. How do you implement role-based authorization in .NET Core?
Answer:
Assign roles to users and use the [Authorize(Roles = "Admin")] attribute.

Roles are generally added during identity creation and stored in the identity system (e.g., Identity
Framework or JWT claims).

44. What is the difference between AddControllers() and AddMvc()?


Answer:

 AddControllers(): Registers only API controllers (no Razor views, minimal MVC
features).
 AddMvc(): Registers full MVC pipeline including Razor Pages, controllers, views, filters.

For APIs, prefer AddControllers() for better performance.

45. What is the use of ModelState.IsValid?


Answer:
Checks if the posted data passed all validation rules (based on data annotations).
If false, validation errors are stored in ModelState.

46. What are Razor Components?


Answer:
Razor Components are building blocks in Blazor used to create UI elements using .razor files.

 They combine HTML and C#


 Enable component-based web development
 Can be nested and reused
Example:

47. How do you manage secrets in ASP.NET Core?


Answer:
In development, use the Secret Manager tool to store secrets outside the codebase.

In production, use environment variables or Azure Key Vault.

48. What are environment variables in .NET Core and how are they used?
Answer:
Used to configure app behavior (e.g., Development, Staging, Production).
49. How does routing work in Minimal APIs?
Answer:
Introduced in .NET 6+, Minimal APIs define routes without controllers:

Great for lightweight services and microservices.

50. What is the Minimal API pattern in .NET 6+?


Answer:
A simplified way to build HTTP APIs without controllers or heavy MVC setup.
Best suited for microservices, internal APIs, or quick prototypes.

Advantages:

 Less boilerplate
 Better performance
 Quick setup

51. What is the difference between TempData, ViewBag, and ViewData?


Answer:

Feature TempData ViewBag ViewData


Current request only
Persistence Until next request Current request only
Dictionary<string, object>
Type Dictionary<string, object> Dynamic
Use case Redirect scenarios Simple view data passing Similar to ViewBag
52. What is FromServices attribute in .NET Core?
Answer:
Injects services into controller actions directly from the DI container.

Useful for optional or localized service injection.

53. How do you implement custom validation in ASP.NET Core models?


Answer:
Create a class inheriting from ValidationAttribute:

54. What is the difference between APIController and ControllerBase?


Answer:

 [ApiController]: Adds automatic model validation, binding, etc.


 ControllerBase: Base class for Web API controllers (no View support).
 Controller: Used for MVC controllers (Views + API).
55. What is the UseDeveloperExceptionPage() middleware?
Answer:
Displays detailed exception information in the browser.
Use only in Development:

56. How do you handle file uploads in ASP.NET Core?


Answer:
Use IFormFile in action methods:

Ensure form uses enctype="multipart/form-data".

57. How do you create and use strongly typed configuration settings in .NET Core?
Answer:

1. Define a POCO:
2. Bind config section in Program.cs:

3. Inject using IOptions<MySettings>.

58. What is IActionResult vs ActionResult<T>?


Answer:

 IActionResult: Flexible return type for different HTTP responses


 ActionResult<T>: Combines HTTP response + a specific return type

59. How do you consume a Web API using HttpClient in .NET Core?
Answer:

Register with services.AddHttpClient<ApiService>().


60. What are ViewComponents in ASP.NET Core?
Answer:
Reusable components that render HTML (like partial views + controller logic).

Example:

Called in Razor: @Component.InvokeAsync("Cart")

61. What are the different ways to deploy a .NET Core application?
Answer:
.NET Core apps can be deployed in two main ways:

1. Framework-dependent deployment (FDD):


o Smaller package
o Runs on machines that have .NET installed
o Example:
2.

Self-contained deployment (SCD):


o Includes the .NET runtime and libraries
o Larger in size
o Runs independently of the machine’s environment
o Example:

Also supports Docker container deployment and Azure App Services.


62. What is the difference between Controller and ControllerBase in ASP.NET Core?
Answer:

Feature Controller ControllerBase


Inherits from ControllerBase Object
Use Case MVC apps (views + APIs) Web APIs only
View support Yes No
Attributes [Controller], [ViewResult] [ApiController]

Use ControllerBase for API-only projects to reduce overhead.

63. What is the Configure() method used for in Startup.cs?


Answer:
Defines the HTTP request pipeline by configuring middleware.
Middleware is executed in the order they are added.

Example:

64. What is the ConfigureServices() method for?


Answer:
Used to register services and configure the dependency injection (DI) container.

Example:

This method is called by the runtime before the pipeline is set up.
65. How does Dependency Injection work in ASP.NET Core?
Answer:
ASP.NET Core has a built-in, lightweight IoC (Inversion of Control) container.

1. Register services in ConfigureServices():

2. Inject into constructors:

The container resolves and provides the service when the controller is instantiated.

66. What is the default lifetime for services in .NET Core DI?
Answer:
There are three lifetimes:

 Transient: A new instance every time (stateless)


 Scoped: One instance per HTTP request
 Singleton: One instance for the entire application lifecycle

67. What is the difference between IOptions<T> and IConfiguration?


Answer:
Feature IOptions<T> IConfiguration
Strong typing Yes (binds config to class) No (string-based access)
Usage Access settings via model class Access config via keys
Best for Complex config (nested settings) Simple flat values or debugging

Use IOptions<T> for maintainability and IntelliSense support.

68. What is IWebHostEnvironment?


Answer:
Used to access environment-specific details in ASP.NET Core apps.

Example usage:

It provides values like Development, Production, or Staging.

69. What is the difference between Razor Pages and MVC?


Answer:

Feature Razor Pages MVC


Structure Page-focused Controller-focused
URL Handling Maps to physical .cshtml files Maps to controller/action
Use Case Simple apps, forms, CRUD Complex apps, REST APIs

Razor Pages are simpler and great for smaller UI-driven apps.

70. What is ViewComponent and when should it be used?


Answer:
ViewComponent is like a partial view with controller logic.
Use when:
 You need to reuse a UI part with some logic
 You want to encapsulate logic and HTML
 It doesn't require routing or a full page

Example:

71. What is the purpose of app.UseAuthorization()?


Answer:
Adds the Authorization middleware to the request pipeline.

It checks whether the current user has permission to access a particular endpoint. Must be used
after UseAuthentication() and before UseEndpoints().

72. What are the return types of controller actions in ASP.NET Core?
Answer:
Common return types:

 IActionResult
 ActionResult<T>
 JsonResult
 ViewResult
 RedirectResult
 ContentResult
 FileResult

Example:
73. What is a PartialView in MVC and when to use it?
Answer:
A reusable view (.cshtml) without layout, used for rendering part of the page.

Use cases:

 Repeating sections (e.g., menu, sidebar, footer)


 AJAX partial updates

Render using:

74. How do you secure an API using JWT in .NET Core?


Answer:

1. Install Microsoft.AspNetCore.Authentication.JwtBearer
2. Configure in Program.cs:
3. Add [Authorize] to secure endpoints.

75. What are custom filters and how do you create one?
Answer:
Custom filters allow you to run code before/after controller actions.

1. Implement a filter:

2. Register globally:

76. How can you enable Caching in ASP.NET Core?


Answer:

 In-memory caching:
 Response caching (using app.UseResponseCaching())

77. What is an anti-forgery token and how is it used?


Answer:
Prevents Cross-Site Request Forgery (CSRF) attacks.

In Razor views:

In controllers:
ASP.NET Core includes automatic CSRF protection.

78. How do you serve static files from a custom folder?


Answer:
Use UseStaticFiles with custom StaticFileOptions:

Then access via: http://localhost:5000/Static/file.txt

79. What is the purpose of app.UseHttpsRedirection()?


Answer:
Automatically redirects all HTTP requests to HTTPS.
Improves security by enforcing encryption.

Used in production environments:

80. How do you return custom HTTP status codes in API responses?
Answer:
These methods come from ControllerBase and improve API expressiveness.

81. What is the difference between AddSingleton, AddScoped, and AddTransient in


dependency injection?
Answer:

Lifetime Description Use Case


One instance shared throughout the application's
Singleton Configuration, caching services
lifetime
Database contexts, user session
Scoped One instance per HTTP request
data
Transient New instance every time it's requested Lightweight, stateless services

Example:

82. What is Middleware in ASP.NET Core?


Answer:
Middleware is software that handles HTTP requests/responses in the request pipeline.

Each middleware can:

 Perform an action (e.g., logging, authentication)


 Call the next middleware (await next())

Example:
83. How do you create a RESTful API in ASP.NET Core?
Answer:

1. Create a controller:

2. Register services in Program.cs


3. Run the app and use tools like Postman to test.

84. What is appsettings.json and how is it used?


Answer:
A JSON configuration file used to store application settings.

Example:

Access:
Use IOptions<AppSettings> for strongly-typed access.

85. What is the difference between app.Use and app.Run?


Answer:

 app.Use: Adds middleware that can pass control to the next delegate
 app.Run: Terminates the pipeline (no next)

86. How do you enable response compression in ASP.NET Core?


Answer:

1. Install Microsoft.AspNetCore.ResponseCompression
2. In Program.cs:

Improves performance by reducing response size.


87. What is Kestrel in ASP.NET Core?
Answer:
Kestrel is a cross-platform, high-performance web server used as the internal server in ASP.NET
Core.

 Runs directly with .NET Core


 Can be used with IIS, NGINX, or standalone
 Configurable via appsettings.json

88. What is HSTS and how do you configure it?


Answer:
HSTS (HTTP Strict Transport Security) forces HTTPS connections.

Configure in Program.cs:

Used only in production. Enhances security by telling browsers to use HTTPS.

89. How do you protect sensitive data like connection strings?


Answer:

 Store in environment variables or Azure Key Vault


 Use Secret Manager for development
 Use user-secrets in .NET CLI:

Never commit sensitive info in source control.

90. What are endpoint filters in Minimal APIs (.NET 7+)?


Answer:
Endpoint filters allow request/response transformations or validation logic in Minimal APIs.
Similar to action filters in MVC.

91. What is async/await and how does it work in .NET Core?


Answer:
async and await allow non-blocking execution.

Example:

Improves scalability by freeing up threads during I/O-bound operations.

92. How do you add Swagger to your ASP.NET Core API?


Answer:

1. Install Swashbuckle.AspNetCore
2. In Program.cs:

Access at /swagger endpoint. Useful for testing and API documentation.


93. What is Cross-Origin Resource Sharing (CORS)?
Answer:
CORS allows your API to be accessed from different domains.

Configure:

Used when frontend and backend are hosted on different origins.

94. What is IServiceCollection?


Answer:
A built-in .NET Core interface that represents the DI container.

 Used in Program.cs to register dependencies


 Supports scopes like Singleton, Scoped, Transient

95. How do you validate a model in Web API?


Answer:

1. Use [ApiController] attribute


2. Use data annotations:

The framework automatically checks model validity and returns 400 if invalid.
96. What is the [FromBody], [FromQuery], [FromRoute] attribute?
Answer:

Attribute Description
[FromBody] Binds data from the request body (JSON)
[FromQuery] Binds from query string
[FromRoute] Binds from route parameter

Example:

97. What is Entity Framework Core?


Answer:
EF Core is an ORM that simplifies database access by mapping .NET objects to database
records.

 Supports LINQ queries


 Handles CRUD operations
 Can work with migrations

98. How do you apply database migrations in EF Core?


Answer:

1. Create migration:

2. Apply migration:

Migrations track schema changes and apply them to the DB.


99. What is DbContext in EF Core?
Answer:
DbContext represents a session with the database. It allows querying and saving data.

Example:

100. What are some best practices for building APIs in ASP.NET Core?
Answer:

 Use [ApiController] and attribute routing


 Validate models with data annotations
 Use versioning
 Use middleware for error handling
 Use logging with Serilog or NLog
 Secure with HTTPS and authentication (e.g., JWT)

You might also like