ASP.NET CORE MVC WITH ADO.NET - Interview Questions and Answers
Core Concepts & Fundamentals (1-15)
1. What is ASP.NET Core MVC, and what are its main advantages?
Answer: ASP.NET Core MVC is a modern, cross-platform, high-performance, open-source framework for building web applications and APIs using the Model-View-Controller pattern. Its advantages include a clear separation of concerns, full control over HTML, high testability, and a lightweight, modular HTTP request pipeline.
2. Explain the Model-View-Controller (MVC) pattern in detail.
Answer:
Model: Represents the application's data and business logic. It is responsible for retrieving data from a database (often via ADO.NET) and enforcing business rules.
View: A template that renders the user interface (UI) using HTML and Razor syntax. It displays data from the Model.
Controller: Handles user interactions. It processes incoming HTTP requests, works with the Model to get data, and selects the appropriate View to render, passing the Model to it.
3. What is Dependency Injection (DI), and why is it central to ASP.NET Core?
Answer: DI is a design pattern that is a fundamental part of ASP.NET Core. It's a technique for achieving Inversion of Control (IoC) between classes and their dependencies. The framework provides a built-in IoC container that manages the creation and lifetime of objects. This promotes loose coupling, makes applications more testable and maintainable, and is used pervasively throughout the framework itself.
4. Explain the role of the Program.cs file in .NET 6/8. What happened to Startup.cs?
Answer: In .NET 6 and later, the Startup.cs file has been removed and its functionality has been consolidated into the Program.cs file using a "minimal hosting model." This single file now uses a top-level statement style to:
Configure and build the host and application services (previously
ConfigureServicesinStartup).Configure the application's request processing pipeline (previously
ConfigureinStartup).
5. What is the purpose of the appsettings.json file and the IConfiguration service?
Answer: The appsettings.json file is the primary configuration file for an ASP.NET Core application. It stores settings like connection strings, logging levels, and custom application settings in a JSON format. The IConfiguration service is injected into classes to provide read-only access to the configuration data stored in this file and other sources (like environment variables).
6. What are Tag Helpers? Why are they preferred over HTML Helpers?
Answer: Tag Helpers are server-side components that enable server-side code to participate in creating and rendering HTML elements in Razor files. They are preferred because:
They provide an HTML-friendly development experience, looking like standard HTML tags.
They offer better IntelliSense support in modern HTML editors.
They are more readable and maintainable, as they blend seamlessly with HTML.
7. Explain the various types of Filters in ASP.NET Core MVC.
Answer: Filters allow you to run code at specific stages in the request processing pipeline.
Authorization Filter: Runs first to determine if the user is authorized (e.g.,
[Authorize]).Resource Filter: Runs after authorization. Good for caching or short-circuiting requests for performance.
Action Filter: Runs immediately before and after an action method executes. Common for logging or modifying action arguments/results.
Exception Filter: Used to handle unhandled exceptions before the response is sent.
Result Filter: Runs before and after the execution of the action result (e.g., before the view is rendered).
8. What is Routing? Explain the difference between Convention-based and Attribute Routing.
Answer: Routing maps incoming browser requests to specific controller action methods.
Convention-based Routing: Defined globally in
Program.csusingMapControllerRoutewith a template like"{controller=Home}/{action=Index}/{id?}".Attribute Routing: Defined using attributes like
[Route],[HttpGet], and[HttpPost]directly on controllers and actions. This is the more explicit, flexible, and preferred method in modern ASP.NET Core MVC development.
9. What is the difference between IActionResult and ActionResult?
Answer: IActionResult is an interface that defines a contract for an action result. ActionResult is a base class that implements IActionResult and provides helper methods to return various results like View(), Json(), File(), RedirectToAction(), etc. While you can return IActionResult, using ActionResult as the return type is common as it's more convenient.
10. How does Model Binding work in ASP.NET Core?
Answer: Model Binding is an automatic process where ASP.NET Core takes data from an HTTP request (form values, route data, query strings, uploaded files, etc.) and uses it to create .NET objects, which are then passed as parameters to an action method. It works by matching the names of the model's properties to the names of the values in the request.
11. What is a ViewModel, and how is it different from a Domain Model?
Answer: A ViewModel is a class specifically designed for a View. It contains only the data needed for that view, which might be a combination or a subset of data from one or more Domain Models. A Domain Model represents the core business entities and logic, while a ViewModel represents the view's presentation data, often flattening or shaping the domain data for the UI.
12. How do you perform Model Validation in ASP.NET Core MVC?
Answer: Validation is done using Data Annotations from the System.ComponentModel.DataAnnotations namespace. Attributes like [Required], [StringLength], [Range], and [EmailAddress] are applied to Model/ViewModel properties. In the controller's POST action, you check ModelState.IsValid to see if validation passed. The validation errors are automatically displayed in the view using asp-validation-for Tag Helpers and ValidationSummary.
13. What is Razor Pages, and when would you choose it over MVC?
Answer: Razor Pages is a page-based programming model built on top of the MVC framework. It's ideal for simpler, page-centric scenarios where the logic for each page is self-contained (like a "Contact Us" or "About" page). Use MVC for more complex applications where you need a clear separation of concerns, reusable controllers across multiple views, and a more structured approach for larger teams.
14. Explain the concept of Middleware in ASP.NET Core.
Answer: Middleware are software components that are assembled into an application pipeline to handle requests and responses. Each component:
Chooses whether to pass the request to the next component in the pipeline.
Can perform work before and after the next component.
Examples include authentication, static file serving, routing, and custom logging middleware. The order of middleware registration inProgram.csis critical.
15. What is the IWebHostEnvironment service?
Answer: This service provides information about the web hosting environment an application is running in, such as the environment name (e.g., Development, Staging, Production via the ASPNETCORE_ENVIRONMENT variable), application name, and web root path. It's commonly used for conditional logic, like enabling the developer exception page only in development.
Intermediate Concepts & Data Access with ADO.NET (16-35)
16. What is the difference between Transient, Scoped, and Singleton service lifetimes?
Answer:
Transient: A new instance is created every time the service is requested from the service container. Ideal for lightweight, stateless services.
Scoped: A single instance is created per HTTP request and shared throughout that request. This is the default and safe lifetime for services like a database connection context.
Singleton: A single instance is created for the entire application lifetime and shared across all requests. Use only for stateless, thread-safe services.
17. How do you manage user session state in ASP.NET Core?
Answer: Session state is maintained using the ISession service. You must first enable it in Program.cs with builder.Services.AddSession() and app.UseSession(). Data is stored as key-value pairs on the server, and a session cookie is sent to the client to identify the session.
18. How do you enable and configure CORS in ASP.NET Core?
Answer: CORS (Cross-Origin Resource Sharing) is enabled by adding a named policy in Program.cs:
builder.Services.AddCors(options => { options.AddPolicy("AllowMyOrigin", policy => { policy.WithOrigins("https://client-domain.com"); policy.AllowAnyHeader(); policy.AllowAnyMethod(); }); }); // Later, in the pipeline app.UseCors("AllowMyOrigin");
19. What is the Options Pattern?
Answer: The Options Pattern uses classes to provide strongly-typed access to groups of related settings from appsettings.json. You register a configuration section to an options class:
builder.Services.Configure<MyOptions>( builder.Configuration.GetSection("MySection"));
You can then inject IOptions<MyOptions> into your controllers or services to access the settings.
20. Explain the concept of Areas in ASP.NET Core MVC.
Answer: Areas provide a way to partition a large ASP.NET Core MVC application into smaller functional groupings. Each area has its own folder structure for controllers, views, and models, and can have its own routing configuration. This is extremely useful for organizing complex applications, e.g., having separate Admin, Customer, and Public areas.
21. How do you handle errors globally in ASP.NET Core?
Answer:
Development: Use
app.UseDeveloperExceptionPage()to get detailed error information.Production: Use
app.UseExceptionHandler("/Error")to route exceptions to a safe error-handling page.HTTP Status Codes: Use
app.UseStatusCodePagesWithReExecute("/Error/{0}")to handle status codes like 404 (Not Found) and 500 (Internal Server Error) by re-executing the request pipeline to a specific path.
22. What is Caching? Describe the different types of caching in ASP.NET Core.
Answer: Caching is a technique to store frequently accessed data for fast retrieval.
In-Memory Caching: Stores data in the memory of the web server using
IMemoryCache. Fast but not shared across multiple servers.Distributed Caching: Stores data in an external, shared cache (like Redis or SQL Server) using
IDistributedCache. Used in web farm scenarios.Response Caching: Caches the entire HTTP response based on cache-related headers. Uses the
[ResponseCache]attribute.
23. What is the difference between TempData, ViewData, and ViewBag?
Answer:
ViewData: A dictionary (
ViewDataDictionary) that passes data from a controller to a view. It's loosely typed and requires casting. Exists only for the current request.ViewBag: A dynamic wrapper around
ViewData. It's also loosely typed but doesn't require casting. Exists only for the current request.TempData: Based on
ITempDataProvider, used to store data until it is read in a subsequent request. It's perfect for redirects, like in the Post-Redirect-Get (PRG) pattern. It uses either cookies or session state by default.
24. How do you implement Authentication and Authorization in ASP.NET Core?
Answer:
Authentication (Who are you?): Use
AddAuthenticationto configure a scheme (e.g., Cookies). ASP.NET Core Identity is a full-featured API for user authentication (login, registration, etc.).Authorization (What are you allowed to do?): Use the
[Authorize]attribute on controllers or actions. You can create policies for more granular control (e.g.,[Authorize(Policy = "RequireAdminRole")]).
25. How do you create a Custom Middleware?
Answer: A custom middleware can be a class with an InvokeAsync method or a simple inline lambda.
// Inline Middleware app.Use(async (context, next) => { // Do work before the next middleware. await next.Invoke(); // Call the next middleware // Do work after the next middleware. }); // Class-based Middleware public class CustomMiddleware { private readonly RequestDelegate _next; public CustomMiddleware(RequestDelegate next) => _next = next; public async Task InvokeAsync(HttpContext context) { await _next(context); } }
26. What are the core ADO.NET objects used for data access?
Answer: The primary objects are:
SqlConnection: Establishes a connection to a SQL Server database.SqlCommand: Represents a SQL statement or stored procedure to execute.SqlDataReader: Provides a forward-only, read-only stream of data from the database.SqlDataAdapter: A bridge between aDataSetand the database, used to fill aDataSetand update the database.SqlParameter: Represents a parameter to aSqlCommand, crucial for preventing SQL injection.
27. How do you properly manage database connections using ADO.NET in ASP.NET Core?
Answer: The key is to ensure connections are closed properly. The best practice is to use the using statement, which ensures the SqlConnection is disposed (and thus closed) even if an exception occurs.
using (var connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); // Execute your database commands here } // Connection is automatically closed and disposed here.
28. What is the purpose of the ExecuteScalar and ExecuteNonQuery methods?
Answer:
ExecuteScalar(): Executes the query and returns the first column of the first row in the result set. It's ideal for singleton queries likeCOUNT(*),SUM(), or retrieving a single value.ExecuteNonQuery(): Executes a command (like INSERT, UPDATE, DELETE) and returns the number of rows affected. It does not return a result set.
29. Explain how you would use a SqlDataReader to retrieve data.
Answer: The SqlDataReader is used for high-performance, forward-only reading of data.
using var command = new SqlCommand("SELECT * FROM Products", connection); using var reader = await command.ExecuteReaderAsync(); while (await reader.ReadAsync()) { var productName = reader["Name"].ToString(); var unitPrice = reader.GetDecimal(reader.GetOrdinal("UnitPrice")); // ... process data }
30. Why is it critical to use parameters in SQL commands? How do you use SqlParameter?
Answer: Using parameters is the primary defense against SQL Injection attacks. It ensures user input is treated as a data value, not executable SQL code.
var command = new SqlCommand("SELECT * FROM Users WHERE Username = @Username", connection); command.Parameters.AddWithValue("@Username", userInputUsername); // This safely handles the input, even if it contains malicious SQL.
31. How can you implement the Repository Pattern with ADO.NET?
Answer: The Repository Pattern abstracts the data layer, making your application more testable and maintainable. You create an interface (e.g., IProductRepository) with methods like GetAll(), GetById(int id), Add(Product product). Then, you create a concrete class (e.g., AdoNetProductRepository) that implements this interface using ADO.NET code. This interface can then be injected via DI into your controllers.
32. How do you handle transactions in ADO.NET?
Answer: You can manage transactions explicitly using the SqlTransaction object.
using var connection = new SqlConnection(connectionString); await connection.OpenAsync(); using var transaction = await connection.BeginTransactionAsync(); try { using var command = connection.CreateCommand(); command.Transaction = transaction; command.CommandText = "INSERT INTO ..."; await command.ExecuteNonQueryAsync(); // ... more commands await transaction.CommitAsync(); // Commit if all succeeds } catch { await transaction.RollbackAsync(); // Rollback on failure throw; }
33. What is the difference between a connected (DataReader) and a disconnected (DataAdapter/DataSet) architecture in ADO.NET?
Answer:
Connected Architecture (
SqlDataReader): Requires an open connection for the entire duration of data access. It's very fast and efficient for read-only, forward-only scenarios. The connection is not available for other uses during this time.Disconnected Architecture (
SqlDataAdapter/DataSet): TheDataAdapteropens a connection, fills aDataSet(an in-memory cache of data), and then closes the connection. You work with theDataSetoffline. Changes can later be reconciled with the database by re-opening the connection and using theDataAdapterto update. This is heavier but allows for offline data manipulation.
34. How would you perform an asynchronous database operation using ADO.NET?
Answer: Use the async versions of the ADO.NET methods, which typically end with the Async suffix, and use the await keyword.
public async Task<List<Product>> GetProductsAsync() { var products = new List<Product>(); using (var connection = new SqlConnection(_connectionString)) { await connection.OpenAsync(); using (var command = new SqlCommand("SELECT * FROM Products", connection)) { using (var reader = await command.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { // ... map data to Product object products.Add(product); } } } } return products; }
35. How do you read the connection string from appsettings.json?
Answer: In Program.cs, the configuration is built and available. You can access the connection string and register it for DI.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddSingleton(connectionString); // Now injectable anywhere // Or, register your repository and pass the connection string to its constructor. builder.Services.AddScoped<IProductRepository>(provider => new AdoNetProductRepository(connectionString));
Performance, Security & .NET 8 Specifics (36-50)
36. What is the new Keyed Services feature in .NET 8?
Answer: Keyed services allow you to register multiple implementations of the same service interface and resolve a specific one using a key (a string or System.Type). This is useful for the Strategy pattern.
builder.Services.AddKeyedSingleton<IDataService, SqlDataService>("sql"); builder.Services.AddKeyedSingleton<IDataService, OracleDataService>("oracle"); // Resolve in a controller with: public MyController([FromKeyedServices("sql")] IDataService dataService)
37. How does .NET 8 improve performance in ASP.NET Core?
Answer: .NET 8 brings significant performance improvements, including:
Native AOT: Enables publishing an app as native code, leading to extremely fast startup and smaller memory footprint (though with some trade-offs).
Enhanced Output Caching: More flexible and powerful caching policies.
HTTP/3 enabled by default: For faster, more reliable connections.
General improvements across the runtime, GC, and JIT compiler.
38. What is Output Caching, and how is it used in .NET 8?
Answer: Output Caching is a middleware that stores the output of an endpoint and serves it for subsequent requests. In .NET 8, it's enhanced. You enable it with app.UseOutputCache() and then decorate controller actions with the [OutputCache] attribute to define caching policies (duration, vary-by, etc.).
39. What is the Problem Details service?
Answer: It's a standard way for HTTP APIs to return error information. Controllers decorated with [ApiController] automatically return a ProblemDetails JSON response for HTTP 400 and other error status codes, which includes a machine-readable type, title, status, and detail.
40. How can you monitor the performance of your ASP.NET Core application?
Answer: Use Application Performance Management (APM) tools like Application Insights, OpenTelemetry, or MiniProfiler. ASP.NET Core also provides built-in metrics and counters that can be exposed for monitoring systems. You can also use logging and custom middleware for timing requests.
41. How do you secure an ASP.NET Core MVC application against common attacks?
Answer:
SQL Injection: Use parameterized queries with
SqlParameter.XSS (Cross-Site Scripting): Encode output automatically with Razor, or use
@Html.Raw()very carefully.CSRF (Cross-Site Request Forgery): Use the
ValidateAntiForgeryTokenattribute and@Html.AntiForgeryToken().Over-Posting: Use input ViewModels with only the bindable properties (
[Bind]attribute) and avoid binding directly to domain models.
42. What is the purpose of the dotnet user-secrets tool?
Answer: The Secret Manager tool allows you to store sensitive data (like API keys, connection strings) during development on your local machine. It stores them outside the project tree, preventing them from being accidentally checked into source control.
43. How can you make your ASP.NET Core application more scalable?
Answer:
Use asynchronous programming (
async/await) in controllers and data access to improve thread pool utilization.Implement caching strategies (in-memory for single server, distributed for web farms).
Use a distributed cache (like Redis) for session state in a web farm.
Offload long-running tasks to background services (e.g.,
IHostedService).Use a CDN for static files.
44. What is the purpose of the [FromServices] attribute?
Answer: It allows you to inject a service directly into an action method as a parameter, instead of injecting it into the controller's constructor. This can be useful for services that are only needed in a single action.
45. How do you handle file uploads in ASP.NET Core MVC?
Answer: Use an <input type="file"> element in a form with enctype="multipart/form-data". In the action method, accept the file as an IFormFile parameter. You can then read the stream and save it to the file system or a database.
public async Task<IActionResult> Upload(IFormFile file) { if (file.Length > 0) { var filePath = Path.GetTempFileName(); using (var stream = System.IO.File.Create(filePath)) { await file.CopyToAsync(stream); } } return RedirectToAction("Index"); }
46. What is the purpose of the StaticFile middleware?
Answer: The StaticFile middleware (enabled with app.UseStaticFiles()) is used to serve static files, such as HTML, CSS, JavaScript, and image files, from the wwwroot folder or other configured locations.
47. How do you implement a custom IActionFilter?
Answer: Create a class that implements IActionFilter or IAsyncActionFilter.
public class CustomActionFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { // Runs before the action method } public void OnActionExecuted(ActionExecutedContext context) { // Runs after the action method } } // You can then apply it as an attribute: [ServiceFilter(typeof(CustomActionFilter))]
48. What is the ResponseCache attribute used for?
Answer: The [ResponseCache] attribute is used to control the HTTP caching headers on the response. It tells client browsers and proxy servers how long they can cache the response. This is different from server-side Output Caching.
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)] public IActionResult Index() { return View(); }
49. How do you create a View Component?
Answer: A View Component is a reusable piece of UI logic, like a sidebar or login panel. You create a class that derives from ViewComponent and has an InvokeAsync method. You then create a corresponding view file in Views/Shared/Components/YourComponentName/Default.cshtml.
50. What is the purpose of the _ViewImports.cshtml and _ViewStart.cshtml files?
Answer:
_ViewImports.cshtml: Used to include common directives (likeusingstatements and Tag Helper imports) across all views, reducing duplication._ViewStart.cshtml: Defines common code that runs at the start of each view's rendering, most commonly used to set the default layout page.
Comments
Post a Comment