Core
Core
• Platform Independence: ASP.NET Core MVC is cross-platform, supporting Windows, macOS, and Linux,
while ASP.NET MVC is Windows-only.
• Performance: ASP.NET Core MVC is more lightweight and offers better performance due to its modular
framework and dependency injection.
• Hosting: ASP.NET Core MVC can be hosted on IIS, Nginx, Apache, Docker, and self-hosted, whereas
ASP.NET MVC is primarily hosted on IIS.
• Dependency Injection: ASP.NET Core MVC has built-in support for dependency injection, unlike
ASP.NET MVC, which requires third-party libraries.
• Configuration: ASP.NET Core MVC uses a unified configuration system based on JSON, environment
variables, or command-line arguments, while ASP.NET MVC uses XML-based web.config files.
pipeline work?
In ASP.NET Core, middleware is a software component that handles HTTP requests and responses.
Middleware is organized into a pipeline, where each component can process the request, pass it to the
next middleware, or short-circuit the pipeline.
• Request Handling: When a request arrives, it's processed by the first middleware in the pipeline.
• Next Middleware: The middleware can either perform an action (like logging, authentication) and then
call next() to pass the request to the next component, or it can terminate the request.
• Response Handling: On the way back, the response is processed by middleware in reverse order,
allowing each component to modify the response.
This pipeline approach is highly flexible, enabling modular and customizable request processing.
3.What is Dependency Injection (DI) in ASP.NET Core? How do you register and use
services using DI?
Dependency Injection (DI) in ASP.NET Core is a design pattern used to manage dependencies between
objects. It promotes loose coupling by allowing an object's dependencies to be injected at runtime,
rather than being hardcoded.
Registering Services:
Services are registered in the ConfigureServices method of the Startup class. There are three main
lifetimes for services:
Singleton: Created the first time they are requested and used for the lifetime of the application
Role: It adds services to the application's dependency injection container. Examples include adding
database contexts, identity services, MVC services, and more.
5.What is Razor Pages in ASP.NET Core? How is it different from MVC pattern?
Razor Pages is a page-based programming model in ASP.NET Core that simplifies the development of
web applications. It is built on top of ASP.NET Core MVC, using the same middleware, routing, and
features, but focuses on page-centric development.
1. Structure: In Razor Pages, each page is self-contained with its view and logic, typically using a .cshtml
file for the UI and a corresponding .cshtml.cs file for the page's logic. In contrast, MVC uses separate
controllers, views, and often view models.
2. Simplicity: Razor Pages are simpler for page-focused scenarios, reducing the need for controllers and
making it easier to handle individual page logic and model binding directly within the page's code-behind
file.
3. Routing: Razor Pages use a different routing convention, with URLs typically mapped directly to the file
structure. For example, a Pages/Products/Details.cshtml file would be accessible via /Products/Details.
4. Use Cases: Razor Pages is well-suited for scenarios where the application logic is more page-focused,
such as form submission or displaying data specific to a page. MVC is often preferred for applications
that require complex routing, multiple views for the same data, or more separation of concerns.
6.How do you handle routing in ASP.NET Core MVC? Explain attribute routing and
convention-based routing.
In ASP.NET Core MVC, routing determines how URL requests are mapped to specific controller actions.
Convention-Based Routing:
• Definition: Uses a centralized route configuration to define URL patterns and how they map to
controllers and actions.
• Usage: This default route matches URLs to controller actions based on a pattern, where Home is the
default controller and Index is the default action.
Attribute Routing:
• Definition: Uses attributes on controllers and actions to define routing directly in the code.
• Usage: Provides more granular control over the routing, allowing for more readable and maintainable
routes. It is especially useful for RESTful APIs and when routes do not conform to standard patterns.
7.What are Tag Helpers in ASP.NET Core? Provide examples of built-in Tag Helpers
and how to create custom Tag Helpers.
Tag Helpers in ASP.NET Core are components that enable server-side rendering of HTML elements. They
provide a way to attach server-side behavior to existing HTML tags, making views more readable and
maintainable.
1. Anchor Tag Helper (<a>): Automatically generates URLs based on controller actions and parameters.
2.Form Tag Helper (<form>): Manages form attributes and anti-forgery tokens.
3.Input Tag Helper (<input>): Binds input elements to model properties, including validation attributes.
Creating Custom Tag Helpers:
Define a Tag Helper Class: Inherit from TagHelper and use the [HtmlTargetElement] attribute to specify
the HTML element or attributes it targets.
[HtmlTargetElement("email")]
output.TagName = "a";
output.Attributes.SetAttribute("href", $"mailto:{Address}");
output.Content.SetContent(DisplayName);
Usage in Razor View: Use the custom tag helper like any other HTML element.
8.Explain the use of View Components and Partial Views in ASP.NET Core MVC.
How do they differ from each other?
View Components and Partial Views in ASP.NET Core MVC are both used to encapsulate reusable view
logic and rendering, but they serve different purposes and have distinct characteristics.
View Components:
• Purpose: View Components are similar to controllers but are designed to render a piece of UI, such as a
sidebar, menu, or a complex data display.
• Usage: They are more powerful than partial views as they can execute code independently, including
calling services, querying databases, and more.
• Structure: Consist of a class that inherits from ViewComponent and a corresponding view.
Partial Views:
• Purpose: Partial Views are used to render a part of the view that can be reused across different views,
such as a header, footer, or a form.
• Usage: They are primarily used for layout purposes and do not have any logic of their own beyond
rendering the view.
• Structure: They are just .cshtml files that can be rendered within other views.
Differences:
• Functionality: View Components can execute more complex logic independently, while Partial Views
are simple view snippets without their own logic.
• Invocation: View Components are invoked through a method call, allowing for dynamic content
rendering, whereas Partial Views are invoked using Html.Partial or Html.RenderPartial.
• Context: View Components can accept parameters and perform actions to prepare data, whereas
Partial Views typically rely on the model passed to the main view.
View Components are more suited for encapsulating and reusing UI components with associated logic,
while Partial Views are ideal for static content and layout purposes.
ASP.NET Core MVC for passing data between controllers and views.
TempData:
• Purpose: Used to store data temporarily across requests, primarily useful for redirection scenarios.
• Lifetime: Data persists until it's read or another request is made, and can survive a single redirect.
ViewData:
• Purpose: Passes data from controller to view and between views within a single request.
• Lifetime: Limited to the current request; data is not preserved across redirects.
• Type: A dictionary object (ViewDataDictionary) that stores data as object, requiring casting when
retrieving. 
ViewBag:
• Purpose: A dynamic property that provides a more convenient way to pass data from controller to
view, similar to ViewData.
• Lifetime: Limited to the current request; like ViewData, it's not preserved across redirects.
• Type: Utilizes the dynamic feature of C#, allowing property-like syntax without casting.
Differences:
• Type Safety: ViewBag is dynamic and doesn't require casting, whereas ViewData requires casting from
object.33
• Ease of Use: ViewBag is more convenient with dynamic properties, but ViewData and TempData offer
more control and type safety.
• Lifetime and Scope: TempData is suited for data that needs to persist across requests (especially after a
redirect), while ViewData and ViewBag are limited to the current request and are mainly for passing data
between a controller and a view within that request.
10. What is ASP.NET Core Identity? How do you implement authentication and
authorization using Identity in ASP.NET Core MVC?
ASP.NET Core Identity is a membership system that provides functionalities for authentication and
authorization in ASP.NET Core applications. It simplifies the implementation of user registration, login,
and role management, and can be customized to meet specific needs.
1. Setup Identity:
Add Identity Services: In the ConfigureServices method of the Startup class, add Identity services and
configure the database context.
2.Configure Middleware:
Set Up Authentication and Authorization: In the Configure method of the Startup class, add the
authentication and authorization middleware.
Register Users: Create a registration page that uses UserManager to create new users
4.Implement Authentication:
Login Users: Create a login page that uses SignInManager for user authentication.
5.Authorize Users:
11.How do you handle form submissions and validation in ASP.NET Core MVC?
Describe the use of model validation attributes.
In ASP.NET Core MVC, form submissions and validation are handled through model binding and data
annotations. Here’s how it works:
Create a Model:
Define a model class with properties that represent the form fields
Define an action method in a controller to handle the form submission. The action method should accept
the model as a parameter and handle both GET (to display the form) and POST (to process the form)
requests.
Create a View:
Create a Razor view to render the form. Use HTML helpers or tag helpers to generate form fields.
12.Explain the concept of Entity Framework Core (EF Core) in ASP.NET Core MVC
for database access. How do you perform CRUD operations using EF Core?
Entity Framework Core (EF Core) is an Object-Relational Mapper (ORM) that provides a way to interact
with databases using .NET objects. It simplifies data access by allowing developers to work with data as
strongly-typed objects rather than raw SQL queries.
DbContext: Represents a session with the database and provides methods for querying and saving data.
It is a bridge between your application and the database.
DbSet<TEntity>: Represents a collection of entities of a specific type that can be queried or updated.
Entity: A class that represents a table in the database. Each property of the class represents a column in
the table.
1.Create:
_context.Add(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
2.Read:
return View(products);
3.Update:
if (ModelState.IsValid)
_context.Update(product);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
4.Delete:
  _context.Products.Remove(product);
  await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
Role-Based Authorization:
• Concept: Grants access based on user roles. Roles are assigned to users, and resources are protected
based on these roles.
• Implementation: Define roles in the system and configure role-based policies in the Startup class. Use
attributes like [Authorize(Roles = "Admin")] to restrict access to controllers or actions based on these
roles.
Policy-Based Authorization:
• Concept: Grants access based on custom policies that can include multiple criteria such as claims,
resource attributes, or other conditions.
• Implementation: Define policies in the Startup class by specifying the requirements. Apply these
policies using attributes like [Authorize(Policy = "Over18")] to enforce custom access rules based on
complex conditions.
Both methods ensure that only authorized users can access specific resources or perform certain actions
within the application.
14.Describe the use of Areas in ASP.NET Core MVC for organizing controllers,
views, and other resources in large applications.
Areas in ASP.NET Core MVC are a way to organize controllers, views, and other resources in large
applications to manage complexity and improve maintainability. They help in structuring large
applications by grouping related functionality into separate modules or sections.
• Purpose:
Organization: Areas help in logically grouping related components, making the application more modular
and easier to manage.
Separation of Concerns: By isolating different parts of an application (e.g., admin functionality, user
management), areas prevent clutter and reduce dependencies.
• Structure:
Folder Structure: Each area has its own folder within the Areas directory, typically containing subfolders
for Controllers, Views, and Models.
Routing: Each area can have its own routing configuration, allowing for area-specific routes.
• Usage:
Define an Area: Create an area by adding a folder under the Areas directory and placing controllers and
views inside it.
Configure Routing: Register area-specific routes in the Startup class to support routing requests to the
appropriate area.
• Example:
An application might have an Admin area for administrative tasks, containing its own set of controllers
and views, and a User area for user-related functionalities.
Using areas allows for better organization and scalability, especially in large applications where different
teams or modules might work on different aspects of the application.
15. How do you work with client-side libraries and frameworks (such as jQuery,
Bootstrap, etc.) in an ASP.NET Core MVC application?
In an ASP.NET Core MVC application, client-side libraries and frameworks like jQuery and Bootstrap are
integrated to enhance the user interface and provide dynamic functionality. Here's how you work with
them:
Include Libraries:
Static Files: Add the library files (e.g., JavaScript, CSS) to the wwwroot directory. This directory is used for
serving static files.
CDNs: Use Content Delivery Networks (CDNs) to include libraries directly in your views by linking to
external sources.
Reference Libraries in Views:
Scripts and Styles: Reference the libraries in your Razor views or layout files using <script> and <link>
tags.
Bundling and Minification: Optionally, use tools to bundle and minify scripts and styles for performance
optimization.
Using jQuery:
Integration: Include jQuery by linking to its CDN or adding the library file to wwwroot. Then, use jQuery
in your scripts to add interactivity and handle DOM manipulation.
Using Bootstrap:
Integration: Include Bootstrap by linking to its CDN or adding the Bootstrap files to wwwroot. Reference
Bootstrap CSS for styling and JavaScript for interactive components.
16. What is ASP.NET Core MVC and how does it differ from ASP.NET MVC?
ASP.NET Core MVC is a framework for building web applications using the Model-View-Controller (MVC)
pattern in ASP.NET Core. It is part of the ASP.NET Core framework, which is a cross-platform,
high-performance framework for building modern, cloud-based, and internet-connected applications.
1. Framework:
ASP.NET Core MVC: Part of the ASP.NET Core framework, which is a complete rewrite of the original
ASP.NET framework. It is cross-platform and can run on Windows, Linux, and macOS.
ASP.NET MVC: Part of the older ASP.NET framework, which is Windows-only and runs on the .NET
Framework.
2. Performance:
ASP.NET Core MVC: Generally offers better performance due to its optimized architecture and modular
design. It includes improvements in handling requests and responses.
ASP.NET MVC: Performance is good but not as optimized as ASP.NET Core MVC due to the older
framework's design.
3. Dependency Injection:
ASP.NET Core MVC: Built-in support for dependency injection (DI), making it easier to manage
dependencies and promote loose coupling.
ASP.NET MVC: Dependency injection is not built into the framework and requires third-party libraries or
manual implementation.
4. Hosting:
ASP.NET Core MVC: Can be hosted on various platforms and servers, including Kestrel (a cross-platform
web server), IIS, Nginx, and Apache.
ASP.NET MVC: Typically hosted on IIS (Internet Information Services) on Windows servers.
5. Configuration:
ASP.NET Core MVC: Uses a new configuration system based on JSON files, environment variables, and
other sources. Configuration is more flexible and unified.
ASP.NET MVC: Configuration is typically handled through web.config files and the .NET Framework’s
configuration system.
6. Modularity:
ASP.NET Core MVC: More modular, allowing you to include only the components you need. It supports a
wide range of middleware and services.
7. Cross-Platform Support:
ASP.NET Core MVC: Cross-platform, allowing development and deployment on Windows, Linux, and
macOS.
ASP.NET MVC: Windows-only, limited to the .NET Framework and Windows servers.
ASP.NET Core MVC: Integrated with ASP.NET Core features like Razor Pages, minimal APIs, and enhanced
routing capabilities.
ASP.NET MVC: Focused on traditional MVC patterns and web forms, with separate libraries for web APIs.
Overall, ASP.NET Core MVC offers a more modern, flexible, and high-performance approach to building
web applications compared to ASP.NET MVC, aligning with the latest development practices and
supporting cross-platform development.
17.Explain the Model-View-Controller (MVC) pattern. How does it work in
• Model:
Definition: Represents the data and business logic of the application. It often includes classes that define
the structure of data (e.g., database entities) and business rules.
In ASP.NET Core MVC: Models are typically POCO (Plain Old CLR Objects) classes that represent data and
interact with the database using Entity Framework Core or other data access technologies. They also
include validation logic and business rules.
• View:
Definition: Responsible for rendering the user interface and presenting data to the user. It is the
component that users interact with.
In ASP.NET Core MVC: Views are Razor files (.cshtml) that combine HTML with C# code to dynamically
generate content. They are responsible for displaying data from models and presenting it in a
user-friendly format.
• Controller:
Definition: Handles user input, processes it (often by interacting with the Model), and determines the
appropriate View to render. It acts as an intermediary between the Model and the View.
In ASP.NET Core MVC: Controllers are classes that derive from Controller base class. They contain action
methods that respond to HTTP requests. These methods interact with the Model and return a View (or a
result like JSON data) for the user.
• Routing:
Request Handling: When a user makes a request to the application, ASP.NET Core MVC uses routing to
determine which controller and action method should handle the request.
Route Mapping: Routes are defined in the Startup class and can be customized using attribute routing or
convention-based routing.
• Controller Actions:
Processing Requests: The matched controller's action method processes the request. It may involve
retrieving or manipulating data using models and performing any necessary business logic.
• Model Binding:
Data Handling: ASP.NET Core MVC automatically binds incoming data (e.g., form submissions, query
parameters) to action method parameters or model properties.
• Rendering Views:
Generating Responses: The action method typically returns a ViewResult or other result types. If
returning a view, the view engine renders the view with data from the model.
Dynamic Content: The view generates HTML based on the model data and returns it to the client.
• Returning Results:
Response: The final HTML generated by the view is sent back to the client as an HTTP response, which
the browser renders.
• Example Workflow:
Routing: The routing middleware maps this request to the ProductsController and the Details action
method.
Controller Action: The Details action method retrieves product data from the model based on the ID.
Model: The model contains logic to fetch the product details from the database.
View: The Details action returns a view with the product data. The view template generates HTML to
display the product information.
Response: The HTML is sent back to the user's browser for display.
In summary, the MVC pattern helps in organizing code in a way that separates concerns, making it easier
to manage and scale applications by isolating data management, user interface, and request handling
into distinct components.
18. What is Middleware in ASP.NET Core? How does the Middleware pipeline
work?
Middleware in ASP.NET Core is a component that is executed during the request processing pipeline. It
handles requests and responses, performs operations such as logging, authentication, and exception
handling, and can modify the request and response objects. Middleware components are executed in
the order they are registered in the application pipeline.
1. Purpose:
Request Processing: Middleware processes incoming HTTP requests and outgoing responses. Each
middleware can handle, modify, or pass on requests and responses.
Cross-Cutting Concerns: Common tasks such as authentication, logging, and exception handling are
handled by middleware.
2. Pipeline:
Request Flow: When an HTTP request is made, it travels through the middleware pipeline. Each
middleware component has the opportunity to handle the request or pass it to the next middleware in
the pipeline.
Response Flow: After the request is processed, the response travels back through the middleware
pipeline in reverse order, allowing each middleware component to modify or handle the response.
3. Middleware Components:
Custom Middleware: You can create custom middleware to handle specific tasks. Custom middleware is
typically added to the pipeline using app.UseMiddleware<T>().
Built-in Middleware: ASP.NET Core provides several built-in middleware components, such as
UseStaticFiles() for serving static files, UseRouting() for routing requests, UseAuthorization() for handling
authorization, and UseEndpoints() for endpoint routing.
In Startup Class: Middleware components are configured in the Configure method of the Startup class.
The order in which middleware is added is crucial as it affects request and response processing.
Order of Execution: Middleware is executed in the order it is added. For example, if UseStaticFiles() is
added before UseRouting(), static file requests will be handled before routing is processed.
19.Can you give an example of a custom Middleware you have created?
Custom Logging Middleware:
Purpose: Logs details of each HTTP request and response, including the request path, query string, and
response status code.
Explanation:
Request Logging: When a request arrives, the middleware captures and logs the details before passing
the request to the next component in the pipeline.
Response Logging: After the request is processed, the middleware captures the response details (e.g.,
status code) and logs them before sending the response back to the client.
Usage: This middleware helps in debugging and monitoring by providing insights into the application's
request and response patterns.
How it Works:
This custom middleware can be registered in the Startup class to ensure it’s part of the request
processing pipeline.
20. What is Dependency Injection (DI) in ASP.NET Core MVC? How do you
Concept:
Purpose: DI provides a way to manage and inject services (like repositories, configurations, and other
components) into your classes, usually through constructors.
Benefits: It helps in managing dependencies more effectively, making your code more modular, testable,
and maintainable.
Register Services:
Configuration: In the Startup class, you use the ConfigureServices method to register services with the DI
container. You specify the service type and its implementation, and configure the service lifetime
(transient, scoped, or singleton).
Inject Services:
Constructor Injection: In your controllers, services can be injected via constructor parameters. ASP.NET
Core will resolve and provide the required dependencies automatically.
Example: In a controller, you can have a constructor that takes IMyService as a parameter, and the
framework will inject an instance of MyService.
Service Lifetimes:
Transient: Services are created each time they are requested. Suitable for lightweight, stateless services.
Scoped: Services are created once per request. Useful for maintaining state within a single request.
Singleton: A single instance is created and shared throughout the application's lifetime. Ideal for services
that are stateless or manage shared resources.
1. ConfigureServices Method:
Purpose: The ConfigureServices method is used to register services and configure the DI container.
Services registered here are available throughout the application's lifetime.
How It Works:
Registration: You use the IServiceCollection parameter to add services. This includes configuring services
for MVC, Entity Framework, logging, and custom services.
Lifetime: Specify the service lifetime—transient, scoped, or singleton—based on the needs of the
service.
Example Steps:
Add Others: Include any other services or middleware required by your application.
22. Explain the difference between conventional routing and attribute routing in
ASP.NET Core MVC.
In ASP.NET Core MVC, routing is used to map incoming HTTP requests to the appropriate controller
actions. There are two main types of routing: conventional routing and attribute routing. Here’s a concise
comparison:
Conventional Routing:
Definition: Uses predefined routes specified in the Startup class, typically within the Configure method.
Routes are defined using patterns that map URL paths to controller actions.
Configuration:
Pattern:
Routes are defined with placeholders, e.g., {controller=Home}/{action=Index}/{id?}.
Flexibility:
Less flexible for individual actions; primarily used for global route patterns affecting the entire
application.
Usage:
Suitable for defining common routing patterns that apply across multiple controllers and actions.
Attribute Routing:
Definition: Uses attributes applied directly to controller actions or controllers to define routes. Provides
fine-grained control over routing at the action level.
Configuration:
Pattern:
Flexibility:
Highly flexible; allows for more specific and varied routing patterns. Routes can be customized on a
per-controller or per-action basis.
Usage:
Ideal for creating routes with specific patterns or when needing to override conventional routing
defaults.
Apply the [Route] attribute to the controller class to set a base route for all actions within the controller.
2. Action-Level Routing:
Apply the [Route] attribute to individual action methods to define specific routes.
You can use route parameters and constraints in the route template.
3.Combining Routes:
Combine controller-level and action-level routes for more complex routing scenarios.
24. What are Controllers in ASP.NET Core MVC? How do you create a
controller?
Controllers in ASP.NET Core MVC are classes responsible for handling incoming HTTP requests,
processing them, and returning responses. They act as intermediaries between the model and the view,
managing the flow of data and user interactions in an application.
1.Purpose:
Action Methods: Controllers contain action methods that respond to requests, return views, or handle
other tasks such as redirecting or performing CRUD operations.
Controllers in ASP.NET Core MVC typically inherit from the Controller base class, which provides common
functionalities like rendering views and handling user inputs.
25.Explain how action methods work in ASP.NET Core MVC. How do you return
different types of responses?
Action Methods in ASP.NET Core MVC are methods within a controller class that handle HTTP requests
and return responses. They process incoming data, interact with the model, and determine what
response to send back to the client.
How Action Methods Work:
Request Handling:
Invocation: Action methods are invoked based on the routing configuration. The method is called when a
request matches the route pattern defined in the routing system.
Parameters: Action methods can accept parameters that are bound from route data, query strings, form
data, or headers.
Return Types:
IActionResult: Represents the result of an action method. It provides flexibility in returning different
types of responses.
ActionResult: A base class for various result types, often used for returning views or other results.
Builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
 .AddCookie(option =>
 option.ExpireTimeSpan = TimeSpan.FromMinutes(60);
 options.LoginPath = “/Account/SignIn”;
 options.AccessDeniedPath = “/Account/SignIn”;
})
app.UseAuthentication();
app.UseAuthorization();
Step3. Validate the Authentication
 CookieAuthenticationDefaults.AuthenticationScheme);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
HttpContext.Session.SetString(“Username”,model.Username);