Content

  • Interview questions and answers

Interview questions and answers

What is ASP.NET Core? ASP.NET Core is a modern, open-source, and cross-platform framework developed by Microsoft for building web applications and services. (also speficy features which are available in notes - session 1)
Differences Between ASP.NET MVC and ASP.NET Core MVC? ASP.NET Core MVC is a modern, cross-platform, high-performance framework that improves upon the older ASP.NET MVC by offering better modularity, built-in dependency injection, and flexible configuration via appsettings.json and middleware pipelines. It supports hosting on multiple servers, including Kestrel, IIS, and even self-hosting, and is designed with cloud deployment in mind. ASP.NET Core MVC also integrates well with modern front-end frameworks and supports real-time applications with SignalR, making it a more versatile and powerful tool for contemporary web development compared to the more Windows-centric and monolithic ASP.NET MVC.
What is the use of Program.cs file?
  • In ASP.NET Core, the Program.cs file serves as the entry point for the application, responsible for configuring the web host, setting up middleware, and bootstrapping the application.
  • Additionally, Program.cs allows for environment configuration, specifying the environment in which the application runs, and hosting configuration, such as choosing the web server and configuring endpoints.
  • Overall, Program.cs plays a important role in the startup process of an ASP.NET Core application
Difference between SDK and runtime in ASP.NET core? The SDK is used for development tasks such as creating, compiling, and testing applications, while the runtime is required for executing .NET Core applications on end-users machines. The SDK includes the runtime along with development tools, while the runtime focuses solely on executing applications.
What is the use of .csproj file?
  • The .csproj file, or C# Project file, encapsulates project configuration, dependency management, build settings, and project structure within a structured XML format.
  • It defines crucial aspects such as the project's name, target framework, dependencies via <PackageReference> elements, build configurations, and the organization of source files and resources.
What is Middleware in ASP.NET Core?
  • Middleware in ASP.NET Core refers to components that form the request processing pipeline. Each middleware component handles an aspect of HTTP request processing, such as authentication, logging, or routing.
  • Middleware is added to the request pipeline in the Configure method of the Startup class using the UseMiddleware extension method of the IApplicationBuilder interface. They are executed sequentially in the order they are added.
  • ASP.NET Core provides built-in middleware for common tasks, but developers can also create custom middleware to implement specific application logic, allowing for flexibility and extensibility in request processing.
What is MVC, explain working? MVC stands for Model-View-Controller, which is a software architectural pattern commonly used in web development.
  • Model: The model represents the data and business logic of the application. It encapsulates the application's data and behavior, and it is responsible for managing the state of the application. Models can interact with databases, web services, or other sources of data.
  • View: The view is responsible for rendering the user interface. It presents the data to the user and handles user interactions such as button clicks or form submissions. Views are typically HTML templates that are populated with data from the model.
  • Controller: The controller acts as an intermediary between the model and the view. It receives user input from the view, processes it using the model, and then updates the view with the results. Controllers handle HTTP requests, invoke appropriate actions on the model, and select the appropriate view to render the response.
What is the use of Controller class?
  • Controller classes in ASP.NET Core manage incoming HTTP requests from clients and contain action methods to process specific requests.
  • Controllers interact with the application's model to perform data manipulation or retrieval tasks, ensuring separation of concerns in the MVC architecture.
  • Controllers define route templates using attributes, determining which action methods respond to which URLs. They return views or data directly to clients, facilitating the dynamic generation of web content.
What is the difference between action method and non action method?
  • Action methods in ASP.NET Core controllers are public methods designated to handle incoming HTTP requests.
  • Non-action methods within controller classes are public methods not intended to handle HTTP requests.
What are the razor views in asp.net core? Razor views in ASP.NET Core are a type of view template used for generating HTML dynamically based on data provided by the controller. Razor is a markup syntax that allows you to embed server-side code (C# or VB.NET) directly into your HTML markup, enabling the creation of dynamic web pages. Razor views have the extension .cshtml and are a key component of the MVC (Model-View-Controller) pattern used in ASP.NET Core web applications.
What is Dependency Injection? Dependency Injection (DI) is a design pattern used in software development, including ASP.NET Core, to achieve loose coupling between components and promote modular, testable, and maintainable code. In DI, a class depends on interfaces or abstractions rather than concrete implementations. Instead of creating its dependencies internally, a class's dependencies are "injected" into it from the outside, typically via constructor parameters or properties.
What is EF Core? Entity Framework Core (EF Core) is a powerful and versatile object-relational mapping (ORM) framework developed by Microsoft. It is designed to simplify the process of working with relational databases in .NET applications by providing a high-level abstraction over the underlying database schema. (also speficy features which are available in notes - session 2)
How to create connection with database using EF core? Refer session 3
What is Kestrel Server in asp.net core? Kestrel is a cross-platform, lightweight, and high-performance web server built for ASP.NET Core. It's the default web server used by ASP.NET Core applications.
  • Cross-Platform: Kestrel is designed to run on multiple platforms, including Windows, Linux, and macOS. This cross-platform capability makes it suitable for hosting ASP.NET Core applications in various environments.
  • High Performance and Efficiency: Engineered for performance, Kestrel efficiently handles a large number of concurrent connections with low resource consumption and fast startup times. Its asynchronous I/O processing ensures high throughput and low latency for serving HTTP requests and WebSocket connections.
  • Lightweight: Kestrel is optimized for low resource usage and fast startup times. It's a lightweight server that can efficiently handle a high volume of concurrent connections, making it well-suited for microservices and containerized applications.
What is Model Binding in asp.net core? Model binding in ASP.NET Core is a mechanism that automatically maps data from HTTP request parameters to action method parameters or properties of a model class. It simplifies the process of handling user input by eliminating the need for manual extraction and conversion of data from the request. When a request is received, ASP.NET Core's model binding system inspects the request data and attempts to match it to the parameters of the corresponding action method, converting the data to the appropriate types as needed. This allows developers to focus on implementing business logic rather than parsing incoming data, enhancing productivity and maintainability of web applications.
Explain binding from form values Binding from form values in ASP.NET Core refers to the process of mapping data submitted through HTML forms to the properties of model classes in the server-side code. When a form is submitted, ASP.NET Core's model binding system automatically extracts the values from the form fields based on their names and matches them to the properties of the designated model class. This simplifies the handling of user input, as developers can define strongly-typed model classes representing the structure of their data, and rely on the framework to populate these models with the corresponding form values. This enables efficient and consistent data handling in web applications, reducing the amount of manual parsing and conversion code required.
Explain binding through query string Binding through the query string in ASP.NET Core involves automatically extracting and mapping data from the URL's query parameters to action method parameters or properties of a model class in the server-side code.
Explain binding through route data Binding through route data in ASP.NET Core involves automatically extracting and mapping data from the URL's route parameters to action method parameters or properties of a model class in the server-side code, facilitating seamless integration of URL parameters into application logic.
Explain ViewBag, ViewData, TempData

ViewBag

  • ViewBag is a dynamic property that allows you to pass data from a controller to a view. It's a dynamic object, meaning you can add properties to it on the fly without defining them beforehand. It's commonly used when you need to pass a small amount of data from a controller action to a corresponding view.
  • We can add any type of data to the ViewBag – strings, integers, objects, etc.

Example : Controller File

using Microsoft.AspNetCore.Mvc;

namespace Test.UI.Controllers
{
    public class ConceptsController : Controller
    {
        public IActionResult Index()
        {
            ViewBag.Message = "Hello, ViewBag!";
            
            return View();
        }
    }
}

Example : View File

@{
    ViewData["Title"] = "Index";
}

<h1>@ViewBag.Message</h1>

ViewData

  • ViewData is a dictionary-like container that allows you to pass data from a controller to a view. Unlike ViewBag, ViewData is a dictionary of key-value pairs, and you need to explicitly cast data types when retrieving them in the view. It provides a way to pass data from the controller to the view without using strongly-typed models.

Example:Controller File

using Microsoft.AspNetCore.Mvc;

namespace Test.UI.Controllers
{
    public class ConceptsController : Controller
    {
        public IActionResult Index()
        {

            ViewData["Message"] = "Hello, ViewData!";

            return View();
        }
    }
}

Example:View File

@{
    ViewData["Title"] = "Index";
}

<h1>@ViewData["Message"]</h1>

TempData

  • TempData is a dictionary-like object used to pass data from the current request to the next request. Unlike ViewData and ViewBag, which are used to pass data from a controller to a view during the same request, TempData persists data for the subsequent request only. After the next request, the data stored in TempData is automatically removed.
  • @Model is used to display the data retrieved from TempData

Example:Controller File

using Microsoft.AspNetCore.Mvc;

namespace Test.UI.Controllers
{
    public class ConceptsController : Controller
    {
        public IActionResult Index()
        {
            TempData["Message"] = "Hello, TempData!";
            return View();
        }

        public IActionResult NextPage()
        {
            string message = TempData["Message"].ToString();
            return View("NextPage", message);
        }
    }
}

Example:View File (Next Page/Method)

@{
    ViewData["Title"] = "NextPage";
}

<h1>@Model</h1>

Difference between- ViewBag, ViewData, TempData

Feature ViewBag ViewData TempData
Usage Dynamic property Dictionary Dictionary
Scope Current request Current request Next request
Data Removal Not required, lasts for the current request Not required, lasts for the current request Automatically removed after the next request
Type Safety No compile-time checking No compile-time checking No compile-time checking
Storage Mechanism In memory In memory By default, in session (can be configured to use cookie-based temp data provider)
Example ViewBag.Message = "Hello, ViewBag!"; ViewData["Message"] = "Hello, ViewData!"; TempData["Message"] = "Hello, TempData!";
What is Session in asp.net core?
  • Session State Management allows you to store and retrieve user-specific data across multiple HTTP requests within the same session.
  • It provides a way to maintain user state throughout their interaction with the web application.
  • Sessions are particularly useful for scenarios such as user authentication, shopping cart data storage, and caching frequently accessed information.
What is repository pattern, explain steps to implement it ? Refer session 5
Explain EF Core relationships Refer session 6
What is the use of appsettings.json file? The appsettings.json file in ASP.NET Core serves as a centralized location for storing configuration settings, such as database connection strings, logging configurations, and other application settings, in a JSON format.
Explain Tag Helpers in asp.net core

Tag Helpers

  • Tag Helpers in ASP.NET Core are a new feature in the Razor syntax that enable server-side code to participate in creating and rendering HTML elements in Razor views.
  • They provide a way to make your views cleaner and more maintainable by reducing the amount of inline C# code mixed with HTML.
  • Built-in Tag Helpers
    • Form Tag Helper: Simplifies the creation of forms and form elements.
    • Anchor Tag Helper: Helps with generating URLs for hyperlinks.
    • Input Tag Helper: Enhances the <input> element by adding attributes and setting values.
    • Label Tag Helper: Generates <label> elements for form fields.
    • Select Tag Helper: Helps create <select> dropdown lists.
    • Validation Tag Helpers: Helps display validation messages and summaries.
  • Custome Tag Helpers : To create a custom Tag Helper, follow these steps:
    1. Create a Tag Helper Class: Create a new class that inherits from TagHelper.
    2. Override the Process Method: Override the Process method to define the Tag Helper's behavior.
    3. Register the Tag Helper: Register the Tag Helper in the _ViewImports.cshtml file.
What is the use of View Components ?

View Components

  • View Components in ASP.NET Core MVC are similar to partial views but offer more functionality and flexibility
  • They are essentially mini-controllers with associated views that can be invoked from within your main views.
  • View Components are useful for rendering complex UI elements or widgets that need their own logic.
How do we manage dependencies in asp.net core? In ASP.NET Core, dependency management is primarily handled through the built-in dependency injection (DI) container. Dependencies, such as services and components, are registered with the DI container
What is the difference between AddSingleton, AddScoped, and AddTransient? Refer session 4
How we can implement security in asp.net core? Implementing security in ASP.NET Core involves several strategies and practices to ensure the application is protected against various threats. Key aspects include:
  • Authentication and Authorization
  • Data Protection : Encrypt sensitive data in transit using HTTPS by configuring SSL/TLS.
  • Anti-Forgery Tokens : Protect against Cross-Site Request Forgery (CSRF) attacks by using anti-forgery tokens in forms. ASP.NET Core provides built-in support for generating and validating these tokens.
  • Middleware and Security Headers
Explain how routing is handled in asp.net? Routing in ASP.NET Core is a system for mapping incoming HTTP requests to specific endpoints in an application, such as controllers and actions. It is configured and managed through a middleware component in the application's request processing pipeline.
Explain validation in asp.net core

Validation

  • Validation ensures that user input meets the specified criteria before processing it further. This helps maintain data integrity and prevents invalid or malicious data from being submitted to the server.
  • Attribute-based Validation: ASP.NET Core provides a set of validation attributes that you can apply to model properties to define validation rules.
  • Model State Validation: When we submit a form in an ASP.NET Core MVC application, the framework automatically binds the form data to the corresponding model properties. After binding, ASP.NET Core MVC validates the model using the applied validation attributes. Validation errors are stored in the ModelState dictionary, which you can access in your controller actions. We can check ModelState.IsValid to determine if the model passed validation.
  • Client-side Validation: ASP.NET Core supports client-side validation using JavaScript and jQuery validation libraries. When client-side validation is enabled, validation rules defined using validation attributes are also applied on the client side, providing immediate feedback to users without the need to submit the form to the server.
What is anti-forgery attack and how to prevent it in asp.net core application? An anti-forgery attack, often referred to as a Cross-Site Request Forgery (CSRF) attack, is a malicious exploit where unauthorized commands are transmitted from a user that the web application trusts. ASP.NET Core provides built-in mechanisms to prevent such attacks by requiring an anti-forgery token for any state-changing operations like form submissions. This token, generated server-side, is included in both the form data (hidden field) and as a cookie. When the server receives a request, it verifies the token from the form against the token in the cookie, ensuring both originate from the same client. To implement this, you add the @Html.AntiForgeryToken() helper in your forms and decorate your controller actions with the [ValidateAntiForgeryToken] attribute. This helps to confirm that the form submissions are legitimate and not forged.
Explain model state in asp.net core In ASP.NET Core, Model State is a mechanism used to track the state of model binding and to validate the input received from users. It plays a crucial role in ensuring that the data submitted by users conforms to the expected data types and validation rules defined in the model.
The ModelState object contains two key properties:
  • IsValid: This property indicates whether the model binding and validation were successful. It returns true if there are no errors; otherwise, it returns false.
  • Errors: This property contains a collection of errors that occurred during the binding and validation processes.
Explain use of ViewModels? ViewModels play a crucial role in ASP.NET Core applications by acting as a bridge between the domain models and the views. They are specifically designed to contain the data that a view requires to render, which may include data from multiple domain models or additional properties that are only relevant to the view.
What are the action filters in asp.net core?

Action Filters

Action filters are used to apply cross-cutting concerns such as authentication, authorization, validation, caching, and exception handling to action methods, enabling modular and reusable application logic.

Action Filter Description
[Authorize] Restricts access to an action method to only authenticated users or users with specific roles.
[AllowAnonymous] Allows access to an action method by anonymous users, even if authorization is globally enabled.
[ValidateAntiForgeryToken] Validates anti-forgery tokens in form submissions to prevent CSRF attacks.
[ActionName] Specifies an alternate name for an action method.
[ServiceFilter] Allows applying a service-based filter to an action method.
[AutoValidateAntiforgeryToken] Automatically validates anti-forgery tokens for all unsafe HTTP methods.
[ExceptionFilter] Serves as the base class for exception filters.
[ResponseCache] Configures caching settings for the response of an action method.
What are the Data Annotations in asp.net core?

Data Annotations

  • Data annotations are attributes that you can apply to model properties to specify constraints, validation rules, formatting options, and other metadata about the data.
  • These annotations provide a convenient way to define rules for your model without writing custom validation logic.
Annotation Description
[Key] Specifies the primary key property for the model. Required for defining entity keys in entity classes.
[Required] Specifies that the property is required. If the value is null or an empty string, it fails validation.
[StringLength(int MaximumLength)] Limits the maximum length of a string property. If the length of the string exceeds the specified maximum length, it fails validation.
[Range(Type Minimum, Type Maximum)] Specifies a range constraint for numeric properties. If the value falls outside the specified range, it fails validation.
[RegularExpression(string Pattern)] Validates that the property value matches a specified regular expression pattern.
[EmailAddress] Validates that the property contains a valid email address format.
[Url] Validates that the property contains a valid URL format.
[DataType(DataType DataTypeName)] Specifies the data type of the property. Useful for specifying how a value should be displayed or edited.
[Compare(string OtherProperty)] Compares the value of the property with the value of another property. Used for confirming passwords or other fields.