Basic ASP.NET Interview Questions and Answers

1. What is ASP.NET?

  • ASP.NET is an open-source web framework developed by Microsoft for building modern web applications.
  • It is a part of the .NET framework and allows developers to create dynamic web pages, applications, and services.
  • ASP.NET supports multiple programming languages like C# and VB.NET. With its robust security features and easy integration with databases, ASP.NET is widely used in enterprise applications
  • Additionally, it offers features like session management, caching, and authentication.

2. What are the different types of ASP.NET applications?

ASP.NET supports various types of applications, including:
1. Web Forms: Traditional event-driven development model for building interactive web applications.
2. MVC (Model-View-Controller): A pattern-based framework that promotes separation of concerns and testability.
3. Web API: A framework for building HTTP-based APIs to enable communication between different applications.
4. ASP.NET Core: A cross-platform, high-performance, and modular framework for modern web apps.
5. Blazor: A framework that allows C# developers to build interactive web UIs using WebAssembly.

3. Explain the ASP.NET page life cycle?

The ASP.NET page life cycle consists of several stages:

1. Initialization: Controls are initialized, and their properties are set.
2. Load: The page loads with its controls and state data.
3. PostBack Event Handling: Handles user interactions like button clicks.
4. Rendering: The page is converted into HTML and sent to the browser.
5. Unload: The page and controls are discarded from memory.
Understanding the page life cycle helps in writing efficient event-driven web applications.

4. What is the difference between ASP.NET Web Forms and ASP.NET MVC?

ASP.NET Web Forms and ASP.NET MVC are two different approaches for building web applications:
1. Web Forms follow an event-driven programming model, while MVC follows the Model-View-Controller pattern.
2. Web Forms use ViewState to maintain state, whereas MVC does not use ViewState, making it lightweight.
3. MVC provides better control over HTML and JavaScript, making it more SEO-friendly.
4. Web Forms use a drag-and-drop approach, while MVC requires more manual coding.
5. MVC is better suited for large applications that require clean separation of concerns.

5. What are ASP.NET server controls?

ASP.NET server controls are special components that run on the server and generate HTML output to be sent to the client browser. Some key server controls include:

1. Standard Controls: Buttons, labels, textboxes, etc.
2. Data Controls: GridView, Repeater, ListView for displaying data.
3. Validation Controls: RequiredFieldValidator, CompareValidator, etc.
4. Navigation Controls: Menu, SiteMapPath for navigating between pages.
5. Login Controls: Used for authentication and authorization.

6. What is ViewState in ASP.NET?

ViewState is a built-in mechanism in ASP.NET Web Forms used to preserve the state of controls across postbacks. It is stored in a hidden field on the page and helps in maintaining user input:

1. ViewState is enabled by default and is useful for retaining data during postbacks.
2. It increases page size since it is stored as an encoded string in the HTML.
3. It is not suitable for storing large amounts of data.
4. Developers can disable ViewState for controls to optimize performance.
5. Unlike session state, ViewState is specific to a single page and does not persist across multiple pages.

7. What is the difference between Server.Transfer and Response.Redirect?

Server.Transfer and Response.Redirect are both used for navigation between pages in ASP.NET, but they work differently:

1. Server.Transfer transfers the request from one page to another on the server-side, without changing the URL in the browser.
2. Response.Redirect sends an HTTP request to the browser, instructing it to navigate to a different URL.
3. Server.Transfer is faster since it avoids an extra round-trip to the client.
4. Response.Redirect is useful for redirecting to external websites.
5. Server.Transfer maintains the original request data, while Response.Redirect starts a new request.

8. What is a PostBack in ASP.NET?

PostBack is the process of submitting an ASP.NET page to the server for processing:

1. It occurs when a user interacts with a control that triggers a server-side event.
2. PostBack allows the page to maintain its state after form submission.
3. It is commonly used in Web Forms applications where controls maintain their values.
4. Developers can prevent unnecessary PostBacks using AJAX techniques.
5. ASP.NET uses ViewState to help retain control values during PostBack.

9. What are HTTP Modules in ASP.NET?

HTTP Modules in ASP.NET are components that execute during the request processing pipeline. They allow developers to modify or inspect HTTP requests and responses.

1. They implement the IHttpModule interface.
2. They are useful for handling authentication, logging, and response filtering.
3. They can be registered in the web.config file.
4. They execute for every request, unlike HTTP Handlers which handle specific types of requests.
5. Examples include authentication modules and session state modules.

10. What are HTTP Handlers in ASP.NET?

HTTP Handlers in ASP.NET are responsible for processing incoming HTTP requests and generating appropriate responses. Some key points about HTTP Handlers:

1. They are classes that implement the IHttpHandler interface.
2. They are used for handling specific types of requests, such as images, XML, or JSON responses.
3. Custom HTTP Handlers can be created to handle requests efficiently.
4. They provide a way to process requests before the page life cycle begins.
5. Common handlers include ashx files for handling AJAX requests.

11. What is the difference between ASP.NET Web Forms and ASP.NET MVC ?

  • ASP.NET Web Forms: Based on a page-controller pattern. Each page (.aspx) has an associated code-behind file (.aspx.cs) that acts as a controller.
  • Abstracts the HTML and HTTP to create a desktop-like experience for web development. Uses ViewState to persist control values between postbacks.
  • ASP.NET MVC: Follows Model-View-Controller architecture: Model: Business/data logic View: User interface Controller:
  • Handles user interaction, works with model, and selects a view Doesn't use ViewState, making it stateless, which is more web-friendly.

12. What is the role of the Global.asax file in ASP.NET?

  • The Global.asax file (also called the ASP.NET application file or Global Application Class) is a special file used to handle application-level events in an ASP.NET application. It's similar to a Main() method for a web application.

Purpose of Global.asax

It allows developers to respond to application-wide events raised by:

  • ASP.NET runtime
  • HTTP application lifecycle
  • Session lifecycle
  • Errors (exceptions)

 Notes

  • Global.asax is optional—you only need it if you want to handle these events.
  • There can be only one Global.asax file per ASP.NET application.
  • The file must be in the root of the application to be recognized by the runtime
  • It inherits from HttpApplication.

13. What is the difference between Session and Application state?

Session State Used to store user-specific information (like login details, cart items). Each user (browser session) gets a separate storage. Use Case: Personalizing experience, shopping cart, user profile info, etc

// Store value

csharp
Session["UserName"] = "John"; // Retrieve value string userName = Session["UserName"].ToString();

Application State Used to store global data accessible by all users. Shared across all sessions. Use Case: Site-wide counters, shared settings, configuration data.

// Store value

csharp
Application["TotalVisitors"] = 100; // Retrieve value int count = (int)Application["TotalVisitors"];



14. What is a Postback in ASP.NET ?

  • A Postback is the process of submitting an ASP.NET web page to the server for processing. It’s typically triggered by a user interaction with a control (like clicking a button), which sends the page data back to the same page on the server

Definition:

Postback is a round-trip from the client (browser) to the server and back to the same page. It's used to process events (like Button clicks) and update the page content accordingly.

When Does Postback Occur?

  • A postback happens when:
  • A server-side control like a Button, DropDownList, or CheckBox triggers an event.
  • The control has AutoPostBack="true" (for controls like TextBox, DropDownList)
  • The page has a __doPostBack() JavaScript function invoked manually.

15. What are ASP.NET Controls?

ASP.NET Controls are server-side components used to build interactive and dynamic web user interfaces in ASP.NET applications. They run on the server and render HTML to the client browser.

Purpose:

  • Simplify form creation, data display, and user interaction.
  • Enable event-driven programming model similar to Windows Forms.
  • Allow reuse and customization through code-behind and properties.

Example of ASP.NET Controls

<asp:TextBox ID="txtName" runat="server"></asp:TextBox><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /><asp:Label ID="lblMessage" runat="server" />


16. What is the difference between Server.Transfer and Response.Redirect ?

  • Server.Transfer transfers the request from one page to another on the server without making a round trip to the client, whereas Response.
  • Redirect sends a new request from the client to a different page.
Syntax Examples
Server.Transfer
Server.Transfer("Page2.aspx");

The browser still shows the URL of the original page (e.g., Page1.aspx), but the content is served from Page2.aspx.

Response.Redirect
Response.Redirect("Page2.aspx");

The browser is instructed to make a new request to Page2.aspx, and the URL changes accordingly.

17. What is ASP.NET Web API?

ASP.NET Web API is a framework provided by Microsoft for building HTTP-based services and APIs that can be accessed from a wide range of clients including browsers, mobile devices, desktop applications, and more.

Purpose
  • To create RESTful services over the HTTP protocol.
  • To expose application data and services to be consumed by other applications or clients (e.g., Angular, React, mobile apps).
  • To support CRUD (Create, Read, Update, Delete) operations via HTTP verbs.
Key Features
  • Supports RESTful architecture using standard HTTP methods like GET, POST, PUT, DELETE.
  • Returns data in formats like JSON or XML (default is JSON).
  • Built on top of the .NET framework and fully supports dependency injection, routing, and model binding.
  • Platform-independent – clients of any technology (JavaScript, iOS, Android, etc.) can consume the API.
  • Easy to test using tools like Postman, Swagger, or curl.

18. What is Razor in ASP.NET?

Razor is a markup syntax used in ASP.NET for embedding server-based code (typically C#) into web pages. It is a core component of ASP.NET Web Pages, ASP.NET MVC, and ASP.NET Core. Razor allows developers to create dynamic and data-driven web content with minimal effort and cleaner syntax.

Key Features of Razor
  • Lightweight Syntax: Razor uses the
    @ symbol to transition between HTML and server-side C# code, making it easy to read and write.
  • Server-side Execution: Razor code is executed on the server, and the resulting HTML is sent to the client’s browser.
  • IntelliSense Support: Razor works with Visual Studio’s IntelliSense, making development more efficient and less error-prone.
  • Separation of Concerns: Razor supports the MVC (Model-View-Controller) architecture, promoting a clear separation between business logic and UI.
  • Security: Razor automatically encodes output to help protect against cross-site scripting (XSS) attacks.
Basic Syntax

Here’s a simple example of Razor syntax within a view:

<h1>Welcome, @Model.UserName!</h1>
<p>Today’s date is: @DateTime.Now.ToString("D")</p>
    

19. What is Entity Framework in ASP.NET?

Entity Framework (EF) is an open-source Object-Relational Mapping (ORM) framework for ADO.NET, developed by Microsoft. It allows developers to work with a database using .NET objects, eliminating the need for most of the data-access code that developers usually need to write.

Key Features
  • Modeling: EF allows developers to model the entities and relationships of a database using classes.
  • Querying: Developers can query data using LINQ (Language Integrated Query), which is strongly typed and easier to maintain.
  • Change Tracking: Automatically keeps track of changes made to objects so that the correct update queries are generated.
  • Schema Generation: Can generate database schema based on the model.
  • Migrations: EF provides a way to evolve the database schema using code-based migrations.

20. What is the role of Web.config in ASP.NET?

The Web.config file is a crucial configuration file used in ASP.NET applications. It contains settings and configurations that control how an ASP.NET web application behaves. These settings include security configurations, database connections, session states, error handling, and much more.

Key Roles and Features
  • Centralized Configuration: Web.config acts as a central place to manage application settings, making it easier to maintain and update the application.
  • Security Settings: It can define authentication and authorization rules, secure connection requirements, and other security-related settings.
  • Custom Error Pages: Allows developers to configure how errors are handled and which custom error pages should be displayed to users.
  • Connection Strings: Database connection strings can be stored securely within the Web.config file, avoiding hard-coding in the application.
  • Session State Management: Configures how session data is stored (InProc, StateServer, SQLServer, etc.).
  • HTTP Handlers and Modules: You can register custom handlers and modules to handle specific HTTP requests.
  • AppSettings: Provides a simple way to store and retrieve key-value configuration data.

21. What is Caching in ASP.NET?

Caching is a technique used to store frequently accessed data in memory to improve the performance and scalability of web applications. In ASP.NET, caching allows pages, data, or parts of a page to be stored so that subsequent requests can be served faster.

Why Use Caching?
  • Reduces server processing time
  • Decreases database calls
  • Improves application performance and user experience
  • Minimizes latency and bandwidth usage
Types of Caching in ASP.NET
  1. Output Caching: Caches the entire output of a page or controller action.
  2. Fragment Caching: Caches portions of a web page (e.g., user controls).
  3. Data Caching (Object Caching): Caches objects, datasets, or results from expensive operations.
  4. Distributed Caching: Cache is stored in a distributed manner across multiple servers (e.g., using Redis).

22. What is Middleware in ASP.NET Core?

Role of Middleware

Middleware plays a crucial role in how an ASP.NET Core application processes HTTP requests. It enables developers to:

  • Inspect, route, or modify incoming requests.
  • Handle authentication and authorization.
  • Serve static files (like HTML, CSS, JavaScript).
  • Log request/response activity.
  • Perform custom logic like error handling or response formatting.
Example of Middleware Configuration
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }

23. What is Dependency Injection in ASP.NET Core?

Dependency Injection (DI) is a design pattern used in ASP.NET Core to achieve loose coupling between classes and their dependencies. Instead of creating instances of dependent classes manually, the framework automatically provides these dependencies, making code easier to manage, test, and scale.

Why Use Dependency Injection?

  • Improves Code Maintainability: By reducing direct dependencies between classes.
  • Enhances Testability: Makes it easier to mock services for unit testing.
  • Promotes Reusability: Services can be reused across different parts of the application.
  • Supports Inversion of Control (IoC): Control of object creation is moved from the class itself to an external component.

How DI Works in ASP.NET Core

ASP.NET Core has built-in support for Dependency Injection. It uses a built-in IoC container to register services and inject dependencies where needed. You configure services in the Startup.cs file using the ConfigureServices method.

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

Tag Helpers are a feature in ASP.NET Core that enable server-side code to participate in creating and rendering HTML elements in Razor views. They make Razor markup more readable and maintainable by allowing HTML-like syntax for dynamic content.

Purpose of Tag Helpers
  • Make Razor views look more like standard HTML.
  • Provide IntelliSense support in Visual Studio.
  • Help maintain consistency in rendering HTML elements.
  • Offer better separation of concerns between markup and server-side code.
How Tag Helpers Work

Tag Helpers are implemented as C# classes that target specific HTML elements. They run on the server and modify the HTML before it’s sent to the client.

25. What is Blazor in ASP.NET?

Blazor is a modern web framework developed by Microsoft as part of ASP.NET Core. It enables developers to build interactive and rich web user interfaces using C# and .NET instead of JavaScript. Blazor uses a component-based architecture and runs in the browser via WebAssembly or on the server using SignalR.

Key Features of Blazor
  • Full-stack C# development: Build both client-side and server-side logic using C#.
  • Component-based UI: Create reusable UI components similar to frameworks like React or Angular.
  • Runs in the browser (WebAssembly): Eliminates the need for JavaScript in many cases.
  • Integration with .NET libraries: Reuse existing .NET libraries and code.
  • Two hosting models: Blazor WebAssembly (client-side) and Blazor Server (server-side).
Blazor Hosting Models
1. Blazor WebAssembly
  • Runs directly in the browser using WebAssembly.
  • Does not require a server connection after the app is loaded.
  • Offers offline support.
  • Heavier initial load compared to server model.
line

Copyrights © 2024 letsupdateskills All rights reserved