ASP.net Interview Question-Beginner
ASP.net Interview Question-Beginner
1. What is ASP.NET?
ASP.NET is a web development framework developed by Microsoft for building dynamic web
applications and web services. It is part of the .NET framework and allows developers to
create robust, scalable, and high-performance websites, APIs, and web applications.
ASP.NET provides an integrated environment for building web-based solutions with various
libraries and tools that simplify tasks like authentication, data access, session management,
and security. One of its main strengths is its ability to create both web applications and web
services using a wide array of programming languages, including C# and Visual Basic.
Architectural Pattern
o Web Forms: Uses an event-driven model, where each page is treated as an
object with events like Load, Click, etc. It is designed to resemble Windows
Forms applications and hides the complexity of HTTP and statelessness
behind the scenes.
o MVC: Follows the Model-View-Controller (MVC) pattern, which is more
structured and emphasizes a separation of concerns. The controller handles
user input, the model handles the data, and the view handles the display of the
data.
State Management:
1
o Web Forms: Includes automatic handling of state, such as View State, which
helps maintain the state of controls across post backs.
o MVC: Does not rely on View State. Each request is stateless by default,
making it more efficient in terms of resource usage.
Control Over HTML:
o Web Forms: Provides controls like Grid View, Drop Down List, and Button,
which generate HTML automatically. While this is easy to use, it can lead to
heavy and complex HTML that might not be fully customizable.
o MVC: Gives complete control over HTML. The developer writes custom views
using HTML and Razor syntax, which allows for more flexible and lighter code.
Testability:
o Web Forms: Testing Web Forms applications is harder due to its tightly
coupled UI and server-side logic.
o MVC: MVC’s separation of concerns allows for better unit testing of the
controller and models.
Learning Curve:
o Web Forms: Easier for beginners to get started with, especially for developers
familiar with Windows Forms applications or Visual Studio.
o MVC: Has a steeper learning curve due to the need for understanding
patterns like MVC and the separation of concerns.
Use Cases:
o Web Forms: Best suited for simple, enterprise-level applications with complex
UI controls, or for developers who prefer rapid application development (RAD).
o MVC: Ideal for modern web applications that require clean, testable code and
greater flexibility in the user interface.
Cross-Platform:
o ASP.NET: Primarily runs on Windows and is tied to the .NET Framework.
o ASP.NET Core: Is cross-platform and can run on Windows, macOS, and
Linux. It’s built from the ground up to support multiple platforms.
Performance:
o ASP.NET: While performant, it is not as fast as ASP.NET Core, especially in
terms of handling high traffic or requests.
o ASP.NET Core: Designed with performance in mind. It is faster and more
optimized for modern web applications, offering better scalability.
Modularity:
2
o ASP.NET: Has a monolithic structure and includes many built-in libraries that
may not always be needed.
o ASP.NET Core: It is highly modular, allowing you to include only the
necessary libraries, reducing the overall size of your application.
Dependency Injection (DI):
o ASP.NET: Dependency Injection is available but is not built-in.
o ASP.NET Core: Has built-in support for Dependency Injection (DI) from the
start, making it easier to manage dependencies in large applications.
Web Server:
o ASP.NET: Uses IIS as the web server, which is tightly coupled with the .NET
Framework.
o ASP.NET Core: Uses Kestrel as its default web server, which is designed to
be cross-platform and lightweight.
Configuration:
o ASP.NET: Uses the Web.config file for configuration, which can be
cumbersome.
o ASP.NET Core: Uses a more flexible configuration system, allowing settings
to be stored in JSON files, environment variables, or other sources.
Deployment:
o ASP.NET: Requires IIS for deployment on Windows servers.
o ASP.NET Core: Can be deployed on a variety of platforms, and it doesn’t
require IIS. It can run behind Nginx or Apache on Linux.
Development Experience:
o ASP.NET: Has a traditional .NET-based project structure with Visual Studio
integrations.
o ASP.NET Core: Embraces a simplified, open-source, and command-line-
based development experience, although Visual Studio also provides full
support.
WebForms simplify the process of building web pages by abstracting away much of the
underlying HTML, CSS, and JavaScript, allowing developers to focus on events and logic
within the page itself.
Controls and events: WebForms use controls like Button, GridView, DropDownList,
etc., to manage user interaction.
3
Postbacks: WebForms allow pages to perform "PostBacks," or round trips to the
server to maintain state.
ViewState: WebForms maintain state between requests by storing control values in
ViewState.
WebForms was primarily used for applications requiring rapid development and built-in
controls. However, with the advent of ASP.NET MVC and ASP.NET Core, WebForms usage
has decreased as developers have shifted to models that offer more control over HTML and
better scalability.
When a user interacts with a WebForm control (such as clicking a button), a PostBack
occurs, and the page is re-executed on the server. This allows the server to handle any logic
or data processing required and then update the page before sending it back to the client.
Postbacks are a key feature of Web Forms, where server-side logic is often tied to UI
components. The framework manages control state across PostBacks through
the ViewState mechanism. While convenient, excessive use of PostBacks can cause
performance issues, especially for complex pages with many controls.
Application_Start: Fired when the application starts up. It's commonly used for
initializing application-wide settings, like configuration or dependency injection.
Session_Start: Triggered when a new session is started. This is useful for session-
specific initialization tasks.
Application_Error: This event is fired whenever an unhandled exception occurs in
the application, allowing you to handle errors globally.
Application_End: Fired when the application shuts down. You can use this event to
clean up resources.
In ASP.NET Core, Global.asax is replaced by the Startup.cs file, where initialization and
configuration logic are defined.
4
1. Web Forms Pages: Used in the Web Forms model, WebForms pages are
composed of controls like GridView, TextBox, and Button, and are typically used for
applications with complex UI interactions.
2. MVC Views: In the MVC (Model-View-Controller) model, views are HTML templates
that display data passed from controllers. Views are created using Razor syntax
(.cshtml files).
3. Web API Pages: ASP.NET Web API pages define RESTful services to handle HTTP
requests (GET, POST, PUT, DELETE) and return data in formats like JSON or XML.
4. Razor Pages: In ASP.NET Core, Razor Pages is a simplified, page-based
programming model where each page (with a .cshtml file) handles its own logic and
data.
5. Blazor Pages: A new paradigm in ASP.NET Core that allows developers to build
interactive web UIs using C# instead of JavaScript.
1. Client Request: A client makes an HTTP request by entering a URL, clicking a link,
or submitting a form.
2. Routing: The request is routed to the correct controller or handler based on the URL
pattern (in MVC or Web API).
3. Processing: The server processes the request, often involving business logic, data
access, and validation. This step may involve reading or writing data to a database.
4. Response Generation: The server generates a response, typically HTML, JSON, or
XML, and sends it back to the client.
5. Client Receives Response: The client (browser) receives the response and renders
the content (e.g., a webpage or API data).
Throughout this process, various stages such as middleware, filters, authentication, and
authorization come into play to handle specific concerns.
1. GET: Used to request data from the server. It is idempotent, meaning repeated
requests with the same parameters should return the same result.
2. POST: Used to send data to the server, typically to create or update resources. Unlike
GET, POST requests can modify server state.
5
3. PUT: Used to update an existing resource or create a resource if it doesn't exist.
4. DELETE: Used to delete a resource on the server.
5. PATCH: Used to apply partial modifications to a resource.
6. HEAD: Similar to GET but only returns the headers, not the body of the response.
This is useful for checking metadata without fetching the actual data.
7. OPTIONS: Used to retrieve the allowed methods for a specific resource.
ViewState works by serializing the values of controls into a hidden field on the page. When
the page is re-rendered, the ViewState is retrieved, deserialized, and applied to the controls,
so they appear as they were before the PostBack.
Key points:
Persistence: ViewState is stored in the page itself, typically in a hidden field, and is
sent to and from the client in each request.
Usage: It's commonly used for maintaining state between round trips to the server in
Web Forms applications.
Limitations: While useful, ViewState can increase the size of the page and impact
performance if not used judiciously.
6
Example: A website might have a header (navigation bar) and a footer common to all pages.
Instead of adding the same header and footer code on each page, you can place it in the
Master Page. The content pages then just define specific sections of content that get
displayed in the predefined layout.
Master Pages are an important concept in ASP.NET Web Forms. In newer ASP.NET
frameworks like MVC, this concept is replaced by Layout pages, which work similarly.
Reusability: Once a user control is created, it can be reused across multiple pages or
other controls. This improves maintainability and reduces redundancy.
Encapsulation: A User Control can encapsulate logic and UI, making it easier to
manage smaller parts of an application.
Data Binding: Like other ASP.NET controls, User Controls support data binding. You
can bind data to the controls within the User Control just like you would with any other
ASP.NET server control.
Code Behind: User Controls have their own code-behind file, similar to Web Forms,
where logic for controlling the behavior of the control can be implemented.
Example: If you have a site-wide navigation menu that should appear on multiple pages, you
can create a User Control for it and include it in any page that requires the menu.
Route Definitions: In ASP.NET MVC, routes are typically defined in the RouteConfig.cs file
(located in the App_Start folder). Each route has a pattern and specifies how the incoming
URL should be mapped to the appropriate controller and action method.
Example:
routes.MapRoute(
name: "ProductDetails",
url: "products/{id}/{name}",
defaults: new { controller = "Products", action = "Details", id =
UrlParameter.Optional, name = UrlParameter.Optional }
);
7
1. URL Matching: When an HTTP request is received, the routing engine checks each
defined route in order to see if the URL matches the pattern. If a match is found, the
request is passed to the specified controller and action.
2. Default Values: Routes can specify default values, such as which controller and
action to use if the URL doesn’t contain specific data.
3. Parameters in the URL: You can use URL parameters in routes to capture dynamic
values, such as product IDs or user names. These values are then passed to the
corresponding controller action as method parameters.
4. Custom Routes: You can define custom routes for specific sections of your website.
This is especially useful for RESTful APIs where the URL structure is often resource-
based (e.g., /api/products/{id}).
Routing helps in building clean, user-friendly URLs and ensures that the right controller action
is invoked based on the request URL.
Session:
Stateful: Session is used to store data on the server-side for a specific user during
their visit (session) to the website.
Server-Side Storage: Session data is stored on the server, and a unique session
identifier (usually stored in a cookie or URL) is used to track the user’s session.
Expiration: The session expires either after a fixed time or when the user closes the
browser.
Use Case: Ideal for storing sensitive or large data like user authentication details or
shopping cart items, as it does not expose this data to the client.
Cookies:
Stateless: Cookies are small pieces of data that are stored on the client’s browser
and sent back to the server with each HTTP request.
Client-Side Storage: Cookies store data on the client-side (in the browser), making
them suitable for retaining data between sessions.
Expiration: Cookies can have an expiration date and can persist even after the
browser is closed, depending on their configuration.
Use Case: Commonly used for things like storing user preferences or authentication
tokens.
In summary, Session is for server-side state management, while Cookies are client-side
storage mechanisms. Sessions offer more security because the data is not exposed to the
client, whereas cookies are suitable for lightweight, persistent data.
Scope:some text
o Session State: Stores data on a per-user basis. Each user has their own
session data that is isolated from other users. This is ideal for tracking user-
specific information like user preferences or login details.
o Application State: Stores data that is shared across all users of the
application. It is global, meaning all users accessing the application can modify
and access the data.
Storage:some text
o Session State: Data is stored either in memory on the server or, in more
complex configurations, in a distributed cache or database.
o Application State: Typically stored in memory on the server and shared
across all sessions.
Lifetime:some text
o Session State: The data in session is valid only for the duration of the user's
session. It expires either when the session times out or when the user closes
the browser.
o Application State: Data in application state is available for the entire lifetime
of the application and is not tied to individual users or sessions.
Use Cases:some text
o Session State: Used for user-specific data like authentication information,
shopping cart contents, etc.
o Application State: Used for application-wide data, such as global settings,
configuration values, or shared resources.
In-Memory Storage: Cache data is stored in the server’s memory, making it very fast
to access.
Expiration and Dependencies: Cached items can have expiration policies (time-
based expiration, absolute expiration) and dependencies (such as file or database
dependencies) to control when the cached data should be invalidated.
Scalability: For larger applications, distributed caching mechanisms (like Redis or
Memcached) can be used to ensure cache is shared across multiple servers.
Performance Boost: Using cache helps reduce response times and load on the
underlying database or data sources, improving the performance of the application.
9
Example:
Cache["ProductList"] = GetProductListFromDatabase();
This caches the result of Get Product List from Database for faster subsequent retrieval.
AJAX: Using AJAX (Asynchronous JavaScript and XML) allows you to send requests
to the server and receive responses without refreshing the entire page. You can use
UpdatePanel in Web Forms or use JavaScript and jQuery for more control in both
Web Forms and MVC.
Preventing PostBack: In Web Forms, PostBack occurs when a form is submitted
and the page reloads. You can prevent PostBack from happening by using JavaScript
or by handling it in the server-side code.
Example (AJAX using jQuery):
$.ajax({
url: 'YourServiceEndpoint',
type: 'GET',
success: function(response) {
// Process response without reloading the page
}
});
10
An ASP.NET Web Service is a component of an ASP.NET application that exposes its
functionality over HTTP, making it available for remote access by clients over the web. Web
services are platform-independent, meaning they can be accessed by any client that
supports web protocols such as HTTP and SOAP.
Simplified Communication: It wraps the calls to the web service, allowing clients to
interact with the service as if they were invoking a local method.
Automatic Serialization/Deserialization: It automatically handles the conversion of
data between the client and the web service using XML or SOAP.
Example: If a web service provides a method like GetProductDetails, the Proxy class would
allow a client to call this method directly, like a local function, without manually handling HTTP
requests or XML serialization.
To create the Proxy class, developers typically add a Web Reference in the client project to
the web service URL, and Visual Studio automatically generates the proxy.
Data Binding: The DataGrid can be easily bound to a data source, such as a
database, a collection, or an array, for displaying data.
11
Sorting: DataGrid allows columns to be sorted in ascending or descending order.
Paging: It can automatically handle pagination by breaking the data into multiple
pages.
Editing and Deleting: DataGrid allows users to edit and delete individual rows
directly from the interface.
Templates: You can define custom templates for displaying data in different ways,
allowing for full control over the UI (e.g., using ItemTemplate, EditItemTemplate).
While GridView is a more advanced and flexible control in ASP.NET (often preferred for new
applications), the DataGrid is still useful for basic data-driven scenarios in Web Forms.
Redirection: It issues a "302" HTTP status code to the client, instructing the browser
to go to the specified URL.
New Request: A new HTTP request is sent from the client to the target page,
meaning the previous page's data (e.g., form data or session variables) may be lost
unless explicitly stored.
Can Be Used with Query Parameters: You can redirect to a URL with query
parameters, such as Response.Redirect("Details.aspx?id=123").
Example:
Response.Redirect("HomePage.aspx");
Note: Response.Redirect stops further execution of the current page, so no code after it is
executed unless Response.End is used.
12
Faster than Response.Redirect: Since it doesn't require a round-trip to the client,
Server.Transfer is faster than Response.Redirect.
Example:
Server.Transfer("NextPage.aspx");
Note: Server.Transfer is typically used when the same request context is needed, or when
you want to avoid a client-side redirect.
13
Key features of DataSet:
DataSet:some text
o Disconnected: A DataSet is disconnected from the data source once it is
filled with data. It can be used offline and can hold multiple tables.
o Memory Usage: It can consume more memory because it stores data in
memory as an entire structure (tables, rows, relations).
o Data Manipulation: Data can be manipulated in a DataSet (e.g., adding,
modifying, or deleting rows). Changes can be pushed back to the database.
o Use Case: Best suited for scenarios where you need to work with multiple
related tables or require the ability to manipulate data offline.
DataReader:some text
o Connected: A DataReader is connected to the data source and retrieves data
in a forward-only, read-only manner.
o Performance: It is faster and more memory-efficient than DataSet because it
doesn’t hold all data in memory; it reads data row-by-row.
o Read-Only: DataReader allows only reading from the data source and cannot
be used to modify data.
o Use Case: Best suited for scenarios where you need fast, forward-only data
retrieval without the need for manipulation or holding multiple tables in
memory.
Summary:
14
Use DataSet when you need to hold and manipulate data offline, especially with
multiple related tables.
Use DataReader when you need fast, read-only access to a single table of data and
don’t require manipulation.
15
o Used in intranet environments where users authenticate based on their
Windows account.
o The server verifies the user's credentials against the Windows operating
system.
3. Basic Authentication:some text
o Sends the username and password with each HTTP request, typically in an
HTTP header.
o Not secure unless used with HTTPS (because credentials are sent in plain
text).
4. Digest Authentication:some text
o Similar to Basic Authentication, but passwords are hashed before being
transmitted.
o More secure than Basic Authentication as it avoids sending passwords in clear
text.
5. OAuth/OpenID:some text
o Used for third-party authentication, where users log in via another service (e.g.,
Google, Facebook, etc.).
o OAuth is a token-based authentication mechanism.
6. Token-based Authentication (JWT):
o Widely used in RESTful APIs where a token (usually a JWT - JSON Web
Token) is issued after the user logs in and is used for subsequent requests.
RESTful: Web API supports REST principles and uses HTTP methods to perform
operations (GET for reading data, POST for creating data, PUT for updating, DELETE
for removing).
JSON/XML Support: It can return data in formats like JSON or XML, making it easy
to integrate with various client applications.
Stateless: Web APIs are stateless, meaning each request is independent, and the
server does not store any session data between requests.
Example of Web API controller:
public class ProductsController : ApiController
{
public IEnumerable<Product> Get()
{
return db.Products.ToList();
16
}
Data binding in WebForms simplifies the process of displaying and managing data in your
application.
3
1. What are the benefits of using the MVC framework in
ASP.NET?
he MVC (Model-View-Controller) framework offers several key benefits in ASP.NET
T
development:
17
1. Separation of Concerns (SoC)
o MVC divides the application into three distinct components: Model (data
layer), View (UI layer), and Controller (logic layer). This separation makes it
easier to manage and maintain the codebase, as developers can focus on
each component independently without affecting others.
2. Testability:
o The separation of concerns allows developers to easily write unit tests for
the Model and Controller components. Since the View is separate, it is
easier to mock or simulate the interaction between the Model and Controller
during testing.
3. Rich Routing System:
o ASP.NET MVC offers a powerful and customizable routing system that allows
you to define clean, SEO-friendly URLs. You can create RESTful URLs that
map to specific controller actions, making your application more intuitive and
search-engine friendly.
4. Flexible Views with Razor:
o The MVC framework uses Razor as its default view engine, which allows
developers to write dynamic HTML markup easily while embedding server-
side logic using simple, clean syntax.
5. Built-in Support for RESTful Architecture:
o ASP.NET MVC is well-suited for creating RESTful services due to its support
for HTTP methods such as GET, POST, PUT, and DELETE. This makes it
ideal for developing APIs and client-server applications.
6. Extensibility:
o MVC allows for great flexibility through the use of filters, custom view engines,
and extensible model binding. You can customize and extend the framework
to meet specific requirements.
7. Multiple View Options:
o While Web Forms relies heavily on controls, MVC allows developers to use
more flexible view options, such as Razor views and partial views, for
constructing complex UI elements.
In summary, ASP.NET MVC offers a structured approach that enhances maintainability,
testability, flexibility, and scalability, making it a preferred choice for large-scale applications
and web services.
Key Features:
18
1. Syntax Simplicity:
1. Model Binding:
o The Razor view engine allows you to bind a Model (C# object) to the view
and display its data dynamically.
<h1>@Model.ProductName</h1>
<p>@Model.Description</p>
1. HTML Helpers:
o Razor supports HTML Helpers, which are reusable methods that help
generate HTML elements dynamically (e.g., form inputs, buttons).
@Html.TextBoxFor(model => model.Name)
1. Layout Pages:
o Razor views can inherit from a layout page to ensure a consistent design
across multiple views.
@layout "_Layout.cshtml"
1. Partial Views:
o Razor allows you to create partial views, which can be reused across multiple
views, reducing redundancy and improving maintainability.
2. Conditional Logic and Loops:
o Razor allows you to use conditional statements and loops within the view,
making it possible to render dynamic content.
@if (Model.Products.Count > 0)
{
<ul>
@foreach (var product in Model.Products)
{
<li>@product.Name</li>
}
</ul>
}
else
{
<p>No products found</p>
}
In summary, Razor views provide a powerful, flexible way to generate dynamic HTML while
maintaining a clean separation of logic and UI.
19
33. What is the purpose of filters in ASP.NET MVC?
Filters in ASP.NET MVC are used to perform cross-cutting tasks at various stages of the
request processing pipeline. Filters allow you to apply reusable logic that can be applied
globally, at the controller level, or at the action method level.
1. Authorization Filters:
o These filters execute before the action method is called and are used to
handle authentication and authorization. For example, the [Authorize] filter
ensures that only authenticated users can access a particular action method
level.Types of Filters in ASP.NET MVC
[Authorize]
public ActionResult Index()
{
return View();
}
1. Action Filters:
o Action filters are executed before and after an action method is called. They
are typically used for tasks like logging or manipulating input data before the
action is executed.
[ActionFilter]
public ActionResult SomeAction()
{
return View();
}
1. Result Filters:
o Result filters are executed before and after the action result is generated.
These filters are useful for modifying the output returned by an action
(e.g., rendering a view or returning JSON).
[ResultFilter]
public ActionResult SomeAction()
{
return View();
}
1. Exception Filters:
20
public ActionResult Details(int id)
{
return View();
}
1. Global Filters:
In summary, filters in ASP.NET MVC help you centralize common tasks like authentication,
logging, and exception handling, improving code reusability and maintainability.
Key Points:
1. ActionResult is an abstract class that serves as a base type for different types of
results, such as ViewResult, JsonResult, RedirectResult, and more.
View Result: Returns a view (HTML) to the client. It is the most common return type used for
rendering views in MVC.
public ActionResult Index()
{
return View(); // Returns a ViewResult
}
Redirect Result: Redirects the client to another URL or action.
public ActionResult RedirectToHome()
{
return RedirectToAction("Index", "Home"); // RedirectResult
}
Json Result: Returns JSON-formatted data, typically used in AJAX responses.
public JsonResult GetData()
{
return Json(new { Name = "John", Age = 30 }, JsonRequestBehavior.AllowGet);
}
Content Result: Returns plain text or other content (like XML).
public ActionResult GetText()
{
return Content("Hello, World!");
21
}
File Result: Used for returning a file to the client, such as a downloadable file.
public FileResult DownloadFile()
{
return File("~/Downloads/sample.pdf", "application/pdf");
}
In summary, Action Result provides flexibility in what type of response an action can return,
making it a cornerstone of ASP.NET MVC for handling various output types.
Key Responsibilities:
1. Handle HTTP Requests: The controller listens for incoming HTTP requests (GET,
POST, etc.) and decides which action method to execute.
2. Interact with Models: The controller fetches data from the model (database,
business logic, etc.) and passes it to the view for display.
3. Return Action Results: After processing the request, the controller returns
an ActionResult (e.g., ViewResult, JsonResult, RedirectResult), which determines
the response sent to the client.
Action Methods: Each action method corresponds to a specific request, where the controller
can perform logic, data retrieval, and validation before returning the response.
public class ProductController : Controller
{
public ActionResult Index()
{
var products = _productService.GetAllProducts();
return View(products);
}
}
1. Try-Catch Blocks:
o Use try-catch blocks within your code to handle exceptions at specific points.
22
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Handle exception
LogError(ex);
Response.Redirect("~/ErrorPage");
}
1. HandleError Attribute:
23
HttpRequest:
HttpResponse:
Key Stages:
24
5. Page Rendering: The page calls the Render method for each control, generating
HTML.
6. Unload: Cleanup of resources occurs.
The page life cycle allows you to perform actions at specific stages, such as data binding,
event handling, and validation.
Web API:
25