ASP.NET Interview Questions


ASP Dot Net Interview Questions

What is ASP.NET?

ASP.NET is an open-source, server-side web application framework designed for web development to produce dynamic web pages. Developed by Microsoft, it allows developers to build robust web applications, websites, and services. ASP.NET provides a rich set of features such as state management, server controls, and security to make web development easier and more efficient.

Explain the ASP.NET page life cycle.

The ASP.NET page life cycle includes several stages: Initialization, Load, Postback event handling, Rendering, and Unload. During Initialization, server controls are initialized. In the Load stage, the page and its controls are loaded. Postback event handling processes any events. Rendering generates the HTML output, and Unload is the cleanup phase.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Initialization phase
        InitializePage();
    }
    // Load phase
    LoadData();
}

private void InitializePage()
{
    // Initialization logic
}

private void LoadData()
{
    // Data loading logic
}

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

 

ASP.NET Web Forms and ASP.NET MVC are both frameworks for building web applications on the .NET platform, but they follow different paradigms and offer distinct features.

Aspect ASP.NET Web Forms ASP.NET MVC
Architecture Event-driven model, similar to Windows Forms. Model-View-Controller (MVC) pattern.
Separation of Concerns Tighter coupling between UI and logic. Clear separation of concerns (Model, View, Controller).
URL Routing URL routing is handled by Page and QueryString. Customizable and flexible URL routing through RouteConfig.
View State Uses View State to maintain state across postbacks. Stateless, relies on query strings, route values, and POST data for state management.
Control-based Development Rich server-side controls and component-based development. Uses HTML, CSS, and JavaScript with a focus on fine-grained control over markup.
Event Handling Server-side events. HTTP verbs and action methods.
Testability More difficult to unit test due to tight coupling. Designed for testability, supports unit testing and TDD.
Performance Can be slower due to View State and server controls. Generally faster, with better performance due to stateless nature and fine-grained control over HTML.
Flexibility Less flexible due to control abstraction. More flexible and extensible.
Learning Curve Easier for beginners familiar with Windows Forms or event-driven programming. Steeper learning curve, especially for those new to MVC and stateless development.
Customization Limited control over HTML rendered by server controls. Full control over rendered HTML.
Community and Ecosystem Established, but less emphasis in recent years. More modern, with strong community support and regular updates.

What is a Postback in ASP.NET?

A Postback is the process of submitting an ASP.NET page to the server for processing. It occurs when a user performs an action, such as clicking a button, that requires server-side processing. The entire page is refreshed, and the server processes the data and sends the updated page back to the client.

What are Web Services in ASP.NET?

Web Services are reusable software components that use standard web protocols such as HTTP and XML to communicate. In ASP.NET, Web Services allow applications to communicate over the web, providing a way to expose functionality to other applications regardless of the platform or programming language.

What is the Global.asax file used for?

The Global.asax file, also known as the ASP.NET application file, is used to handle application-level events such as Application_Start, Application_End, Session_Start, and Session_End. It allows you to write code that responds to application-wide events, making it useful for tasks such as application initialization and cleanup.

How do you manage state in ASP.NET?

State management in ASP.NET can be handled using various methods: ViewState, ControlState, Hidden Fields, Cookies, Session State, and Application State. ViewState and ControlState are used to maintain state within a single page. Cookies, Session State, and Application State are used to maintain state across multiple pages or sessions.

// Using ViewState
ViewState["UserName"] = "John";

// Using Session State
Session["UserID"] = 123;

// Using Cookies
HttpCookie cookie = new HttpCookie("Theme", "Dark");
Response.Cookies.Add(cookie);

What is ViewState in ASP.NET?

ViewState is a method for preserving page and control values between postbacks. It stores the state of the page's controls in a hidden field encoded in base64 format. ViewState enables the retention of user inputs and control settings across postbacks, providing a seamless user experience without reloading data.

Explain the role of Web.config in ASP.NET.

Web.config is an XML file used to configure settings for an ASP.NET web application. It allows you to define configuration settings such as database connections, security settings, session states, error handling, and more. Web.config can also contain application-specific settings and is loaded dynamically at runtime.

What are HTTP Handlers in ASP.NET?

HTTP Handlers are components that process individual HTTP requests. When a request is made to an ASP.NET application, it is handled by an HTTP Handler based on the requested file type. For example, ASPX pages are processed by the Page Handler. Custom HTTP Handlers can be created to handle specific types of requests.

public class MyHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Process HTTP request
        context.Response.Write("Hello from HTTP Handler!");
    }

    public bool IsReusable { get { return false; } }
}

What is an ASP.NET Master Page?

A Master Page is a template for creating a consistent layout across multiple pages in an ASP.NET application. It defines a common structure and design, such as headers, footers, and navigation bars. Content Pages can then be created using the Master Page, allowing developers to maintain a uniform look and feel throughout the application.

Explain ASP.NET AJAX.

ASP.NET AJAX is a set of extensions that enhance the interactivity and responsiveness of web applications. It allows developers to update parts of a web page asynchronously without reloading the entire page. ASP.NET AJAX includes server-side controls, client-side libraries, and tools to improve user experience and performance.

What is the purpose of the UpdatePanel control in ASP.NET AJAX?

The UpdatePanel control is used to enable partial page updates in ASP.NET AJAX applications. It allows sections of a web page to be updated asynchronously without a full page refresh. By placing controls inside an UpdatePanel, only the content within the panel is refreshed, improving performance and user experience.

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

Server.Transfer and Response.Redirect are both used to navigate from one web page to another in ASP.NET, but they work in different ways and have distinct use cases. 

Feature Server.Transfer Response.Redirect
HTTP Request Uses the same HTTP request. Sends a new HTTP request to the browser.
Client-Side Interaction No client-side interaction. Client is aware of the new URL.
URL in Browser URL in browser does not change. URL in browser changes to the new address.
Performance Generally faster because it avoids an extra round-trip. Slower due to the additional round-trip.
Use Case Useful for server-side transfers within the same application. Useful for client-side redirects, different applications, or external URLs.
Data Persistence Can maintain context and state of the original request. New request context; original request state is lost.
Execution Continuation Execution continues on the new page. Execution of the current page ends, and a new request starts.
Cross-Domain Capability Can only transfer within the same server/application. Can redirect to any URL, including external domains.

How do you handle errors in ASP.NET?

Error handling in ASP.NET can be achieved using try-catch blocks, custom error pages, and the Global.asax file. In Web.config, the customErrors section can define custom error pages for different HTTP status codes. Additionally, the Application_Error event in Global.asax can be used to log errors and redirect users to error pages.

What is an ASP.NET Web API?

ASP.NET Web API is a framework for building HTTP-based services that can be consumed by various clients, including browsers, mobile devices, and desktop applications. It supports CRUD operations and RESTful services, making it ideal for creating APIs that expose data and functionality over the web using standard HTTP protocols.

Explain the Model-View-Controller (MVC) pattern.

The Model-View-Controller (MVC) pattern is a design approach that separates an application into three main components: Model, View, and Controller. The Model represents the data and business logic, the View displays the data and UI, and the Controller handles user input and updates the Model and View. This separation enhances maintainability and testability.

// Model (Business Logic)
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

// View (UI)
@model List<Product>
@foreach(var product in Model)
{
    <div>@product.Name - [email protected]</div>
}

// Controller (Intermediary)
public class ProductController : Controller
{
    public IActionResult Index()
    {
        var products = _repository.GetAllProducts();
        return View(products);
    }
}

What is Razor in ASP.NET MVC?

Razor is a view engine in ASP.NET MVC that allows developers to write server-side code using C# or VB.NET within HTML markup. Razor syntax is clean and concise, making it easy to embed code directly in views. It enhances productivity by providing a straightforward way to generate dynamic content in MVC applications.

What is the Entity Framework in ASP.NET?

Entity Framework (EF) is an object-relational mapper (ORM) that enables developers to interact with databases using .NET objects. It abstracts the database layer, allowing developers to work with data using LINQ queries and strongly-typed entities. EF simplifies data access and manipulation, reducing the need for writing complex SQL queries.

Explain the concept of routing in ASP.NET MVC.

Routing in ASP.NET MVC is the process of mapping URL patterns to controller actions. The RouteConfig file defines routes using the RouteCollection class. Each route specifies a URL pattern and corresponding controller and action. Routing enables clean, user-friendly URLs and allows for dynamic URL generation based on application logic.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

What is the purpose of the ConfigureServices method in Entity Framework Core?

The ConfigureServices method in Entity Framework Core is used to configure the DbContext and related services for dependency injection. This method is called by the runtime during application startup and is where the DbContext is added to the service container along with any other services required for database access, such as connection strings and database providers.

What is the purpose of the appsettings.json file in Blazor?

The appsettings.json file in Blazor is used to store configuration settings for a Blazor application. It provides a structured way to define application settings such as API endpoints, authentication options, and environment-specific configurations. The settings defined in appsettings.json can be accessed throughout the application using the Configuration API.

What is the difference between ViewData and ViewBag in ASP.NET MVC?

ViewData and ViewBag in ASP.NET MVC are both used to pass data from a controller to a view:

Feature ViewData ViewBag
Type ViewDataDictionary Dynamic object
Syntax Dictionary-style (key-value pairs) Dynamic properties
Type Safety Requires type casting Does not require type casting
Declaration Declared as ViewData["Key"] Declared as ViewBag.Key
IntelliSense Support Limited Better IntelliSense support
Data Lifetime Only available for the duration of the request Only available for the duration of the request
Usage Context Useful for passing data with more complex types Simpler and more readable syntax for passing simple data

What is SignalR in ASP.NET Core?

SignalR is a real-time communication library for ASP.NET Core that enables bi-directional communication between the server and client over a persistent connection. It allows applications to push data from the server to the client instantly, making it suitable for implementing features such as chat, notifications, and live updates.

How do you use SignalR in ASP.NET Core?

To use SignalR in ASP.NET Core, you first need to install the Microsoft.AspNetCore.SignalR package via NuGet. Then, you create a Hub class that inherits from the SignalR Hub class and define methods that can be called by clients. Clients connect to the Hub using a SignalR client library and can invoke methods on the server and receive messages from other clients.

What is the purpose of the ConfigureServices method in SignalR?

The ConfigureServices method in SignalR is used to configure SignalR services for dependency injection in ASP.NET Core. This method is called during application startup and is where the SignalR services, such as hubs and options, are added to the service container. It allows you to customize SignalR settings and configure additional services required for real-time communication.

How do you secure an ASP.NET application?

Securing an ASP.NET application involves implementing authentication, authorization, and encryption. Authentication verifies user identity, often using forms authentication or OAuth. Authorization ensures users have the necessary permissions. SSL/TLS encrypts data in transit. ASP.NET also provides built-in features such as membership providers and role-based security.

What is the difference between authentication and authorization?

Authentication and authorization are two fundamental concepts in the realm of security, especially in web applications and services. 

Aspect Authentication Authorization
Purpose To verify the identity of a user or entity. To determine the permissions and access levels of a user or entity.
Question Answered "Who are you?" "What can you do?" or "What are you allowed to access?"
Process Involves validating credentials like usernames and passwords, biometrics, or tokens. Involves checking the user's permissions against the resources they are trying to access.
Timing Happens before authorization. Happens after authentication.
Data Used User credentials, such as passwords, biometrics, or authentication tokens. Access control lists (ACLs), roles, policies, or permissions.
Outcome Confirms whether the user is who they claim to be. Determines what resources the authenticated user can access and what actions they can perform.
Example Logging into a system with a username and password. Granting access to read, write, or modify a file or resource based on user roles.

What are Action Filters in ASP.NET MVC?

Action Filters are attributes that allow you to execute code before or after an action method runs in ASP.NET MVC. They provide a way to add cross-cutting concerns such as logging, authorization, and error handling. Common Action Filters include Authorize, HandleError, and OutputCache, which can be applied globally or to specific controllers and actions.

public class LogActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Log action execution start
        Log("Action Executing: " + filterContext.ActionDescriptor.ActionName);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // Log action execution end
        Log("Action Executed: " + filterContext.ActionDescriptor.ActionName);
    }

    private void Log(string message)
    {
        // Logging logic
    }
}

What is Dependency Injection in ASP.NET Core?

Dependency Injection (DI) is a design pattern used in ASP.NET Core to manage the dependencies of components within an application. It allows objects to request dependencies from an external source rather than creating them internally. ASP.NET Core's built-in DI container provides a way to register, resolve, and inject dependencies into classes, promoting loose coupling and testability.

What is the difference between TempData and ViewData?

ASP.NET Core MVC, TempData and ViewData are used to pass data between controllers and views, but they serve different purposes and have different lifetimes and storage mechanisms.

Feature TempData ViewData
Purpose To pass data between actions or from controller to view, and to persist data for the duration of a single request, including redirects. To pass data from a controller to a view within the same request.
Lifetime Lasts until it is read or the session expires, typically used to maintain data between redirects. Lasts only during the current request, typically used to pass data to a view.
Storage Mechanism Uses session storage (typically stored in cookies or in a state server). Uses a dictionary to store data in memory.
Type Safety String-based key-value pairs, requiring type casting when retrieving values. String-based key-value pairs, also requiring type casting when retrieving values.
Access Dictionary-like syntax or dynamic properties. Dictionary-like syntax or dynamic properties.
Usage Suitable for scenarios where data needs to persist across a redirect. Suitable for passing data to a view, similar to ViewBag.
Clearance Data is cleared after it is read. Data is available only during the request and is cleared after the view is rendered.

What is ASP.NET Core?

ASP.NET Core is a cross-platform, high-performance framework for building modern, cloud-based, and internet-connected applications. It is a redesigned version of ASP.NET, providing improved flexibility, modularity, and performance. ASP.NET Core supports Windows, macOS, and Linux, and allows developers to build web applications, APIs, and microservices.

How do you deploy an ASP.NET application?

Deploying an ASP.NET application involves publishing the application to a web server. This can be done using various methods such as FTP, Web Deploy, or cloud services like Azure. The process includes building the application, copying files to the server, configuring IIS, and ensuring necessary dependencies are installed.

What are Tag Helpers in ASP.NET Core?

Tag Helpers are a feature introduced in ASP.NET Core MVC that enables server-side code to participate in creating and rendering HTML elements. They provide a more natural way to work with HTML and Razor syntax by allowing developers to create custom HTML-like elements with associated server-side logic. Tag Helpers enhance readability and maintainability in MVC views.

<!-- Using Tag Helper -->
<form asp-action="Login" asp-controller="Account" method="post">
    <input type="text" asp-for="Username" />
    <input type="password" asp-for="Password" />
    <button type="submit">Login</button>
</form>

What is Middleware in ASP.NET Core?

Middleware is software components that are assembled into an application pipeline to handle requests and responses. In ASP.NET Core, middleware sits between the server and the application and can perform tasks such as routing, authentication, logging, and error handling. Middleware is configured in the Startup class using the app.UseMiddleware method.

How do you perform database operations using Entity Framework Core?

Database operations in Entity Framework Core are performed using the DbContext class, which represents the database session. You can use LINQ queries to query data, and methods such as Add, Update, and Remove to insert, update, and delete records. Changes are tracked by EF Core and can be saved to the database using the SaveChanges method.

What is a Razor Component in ASP.NET Core?

Razor Components (formerly known as Blazor Components) are reusable UI elements built using Razor syntax and C#. They allow developers to create interactive web applications using a combination of server-side and client-side code. Razor Components run on the server and update the UI dynamically using SignalR to maintain a real-time connection with the client.

What is the purpose of the ConfigureServices method in Startup.cs?

The ConfigureServices method in the Startup class is used to configure services that are used by the ASP.NET Core application. This method is called by the runtime before the Configure method and is where services such as MVC, Entity Framework, and authentication are added to the service container using dependency injection.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddControllersWithViews();
    }
}

What is Razor Pages in ASP.NET Core?

Razor Pages is a new feature introduced in ASP.NET Core that allows developers to build web pages with minimal ceremony. It combines the simplicity of Web Forms with the power of MVC by providing a streamlined programming model for creating page-focused web applications. Razor Pages use the Razor syntax for creating dynamic content.

What is the purpose of the appsettings.json file in ASP.NET Core?

The appsettings.json file is used to store configuration settings for an ASP.NET Core application. It provides a structured way to define application settings such as database connections, logging options, and environment-specific configurations. The settings defined in appsettings.json can be accessed throughout the application using the Configuration API.

How do you handle routing in ASP.NET Core?

Routing in ASP.NET Core is configured in the Startup class using the app.UseRouting method. Routes are defined using the Map* extension methods, where * represents the HTTP method (e.g., MapGet, MapPost). Each route specifies a URL pattern and a corresponding action to execute when the pattern is matched. Routing enables clean and SEO-friendly URLs in ASP.NET Core applications.

What is the difference between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI?

ASP.NET Core Dependency Injection (DI), AddTransient, AddScoped, and AddSingleton are three methods used to register services with different lifetimes. Each of these methods determines how and when an instance of a service is created and how long it lives.

Registration Method Lifetime Instance Creation Use Case
AddTransient Transient A new instance is created every time it is requested. Use for lightweight, stateless services. Each request gets a new instance.
AddScoped Scoped A new instance is created once per request (or per scope). Use for services that should be shared within a single request but not across requests.
AddSingleton Singleton A single instance is created the first time it is requested and shared across all requests. Use for services that maintain state or do not need to be recreated.

How do you handle authentication and authorization in ASP.NET Core?

Authentication and authorization in ASP.NET Core are configured using middleware and services. Authentication middleware is added to the pipeline to authenticate requests, typically using cookies, JWT tokens, or external providers like OAuth. Authorization is handled using policies and attributes to restrict access to resources based on user roles or claims.

What is Entity Framework Core?

Entity Framework Core (EF Core) is a lightweight, extensible, and cross-platform version of Entity Framework, Microsoft's object-relational mapping (ORM) framework. It enables developers to work with databases using .NET objects and LINQ queries. EF Core supports multiple database providers, including SQL Server, SQLite, MySQL, and PostgreSQL.

How do you create migrations in Entity Framework Core?

Migrations in Entity Framework Core are used to manage changes to the database schema over time. To create a migration, you use the dotnet ef migrations add command in the Package Manager Console or the .NET CLI. This command generates a code file that represents the changes to the database schema. Migrations can then be applied using the dotnet ef database update command.

What are Razor Class Libraries in ASP.NET Core?

Razor Class Libraries (RCLs) are a type of project in ASP.NET Core that allows you to package and reuse UI components, views, and assets across multiple projects. RCLs contain Razor files, CSS files, JavaScript files, and other static resources that can be shared as a single library. They provide a convenient way to modularize and distribute UI components in ASP.NET Core applications.