Unit 4: Backend Development Using ASP.NET Core - Subjective Questions
CSE253 — .Net Programming • Practice Questions with Detailed Answers
20 questions
Define ASP.NET Core and explain the major features that make it suitable for building modern web applications.
ASP.NET Core is an open-source, cross-platform framework developed by Microsoft for building web applications, web APIs, real-time applications, and backend services.
Major features:
- Cross-platform support: Applications can run on Windows, Linux, and macOS.
- High performance: It uses a lightweight and modular request-processing pipeline.
- Built-in dependency injection: Services can be registered and injected into controllers or other classes.
- Middleware-based architecture: Requests and responses can be processed through a configurable sequence of middleware components.
- Unified framework: The same framework supports MVC applications, Razor Pages, Web APIs, and SignalR applications.
- Environment-based configuration: Settings can be managed using files such as
appsettings.json, environment variables, and command-line arguments. - Integrated security: Authentication, authorization, HTTPS, and data-protection features are supported.
- Razor view engine: Dynamic HTML can be generated using Razor syntax.
- Cloud and container compatibility: Applications can be deployed easily to cloud platforms and containers.
Explain the MVC architecture in ASP.NET Core and describe how the Model, View, and Controller communicate with one another.
MVC stands for Model-View-Controller. It separates an application into three logical components.
- Model: Represents application data, business rules, and validation logic. It may communicate with a database or other data source.
- View: Represents the user interface. In ASP.NET Core MVC, views are commonly written using HTML and Razor syntax.
- Controller: Receives HTTP requests, processes user input, invokes application logic, and selects a response or view.
Communication flow:
- A user sends an HTTP request to a controller action.
- The controller reads route values, query values, form data, or other request information.
- The controller calls model or service operations to retrieve or modify data.
- The controller passes the resulting model or view model to a view.
- The view uses Razor syntax to generate HTML.
- ASP.NET Core sends the generated response to the client.
This separation improves maintainability, testability, reusability, and organization of the application.
Describe the request-processing pipeline in an ASP.NET Core MVC application. How are requests and responses handled?
An ASP.NET Core application processes each HTTP request through a middleware pipeline.
Request processing steps:
- The web server receives the request.
- Middleware components execute in the order in which they are registered.
- Exception-handling middleware can catch application errors.
- HTTPS redirection and static-file middleware may process the request.
- Routing middleware identifies the endpoint and route values.
- Authentication identifies the user, while authorization checks permissions.
- MVC endpoint execution selects a controller and action.
- Model binding converts request data into action parameters or model objects.
- Validation checks whether the bound model is valid.
- The action executes and produces an
IActionResult.
Response processing:
The response travels back through the middleware pipeline in reverse order. Middleware can modify response headers, status codes, cookies, or body content before the response is sent to the client. Common responses include HTML views, redirects, JSON data, files, and HTTP status codes.
What are controllers and actions in ASP.NET Core MVC? Explain their responsibilities with a suitable example.
A controller is a class that handles related HTTP requests. It normally derives from Controller and contains one or more action methods.
An action is a public method that receives a request, performs application processing, and returns an action result.
public class ProductsController : Controller
{
public IActionResult Details(int id)
{
Product product = productService.GetById(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
}Controller responsibilities:
- Receive and interpret requests.
- Coordinate services and models.
- Apply authorization or request-specific rules.
- Select an appropriate response.
- Avoid containing extensive database or presentation logic.
Action results may include View(), RedirectToAction(), Json(), Ok(), NotFound(), BadRequest(), and File().
Explain routing in ASP.NET Core MVC and distinguish between conventional routing and attribute routing.
Routing maps an incoming URL and HTTP method to a controller action.
Conventional routing defines a general route pattern, usually in the application startup configuration:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");A URL such as /Products/Details/5 can therefore map to the Details action of ProductsController with an id value of 5.
Attribute routing places route templates directly on controllers and actions:
[Route("products")]
public class ProductsController : Controller
{
[HttpGet("{id}")]
public IActionResult Details(int id)
{
return View();
}
}Difference:
- Conventional routing is centralized and convenient for standard MVC applications.
- Attribute routing provides precise, local control over URL patterns.
- Attribute routing is especially useful for REST-style APIs and irregular URL structures.
- Both approaches can support route parameters, constraints, HTTP verbs, and optional values.
Explain the Razor view engine and describe the basic syntax used to embed server-side code in an ASP.NET Core view.
The Razor view engine generates dynamic HTML by combining HTML markup with C# code. Razor files usually have the .cshtml extension.
Common Razor syntax:
- The
@symbol begins a C# expression or code block. @Model.Namedisplays a model property.@ifand@elseprovide conditional rendering.@foreachrepeats markup for a collection.@{ }contains a block of C# statements.@usingimports a namespace.@modeldeclares the strongly typed model for a view.
Example:
cshtml
@model Product
@if (Model.IsAvailable)
{
<p>Available</p>
}
else
{
<p>Currently unavailable</p>
}
Razor automatically HTML-encodes normal output, which helps reduce cross-site scripting risks. Html.Raw should be used only with trusted, properly sanitized content.
Describe layouts, sections, and the ViewStart file in ASP.NET Core MVC. How do they help organize views?
A layout is a shared template containing common page elements such as navigation, headers, footers, stylesheets, and scripts. It commonly contains @RenderBody() for the main view content.
Example layout elements include:
cshtml
<!DOCTYPE html>
<html>
<body>
<header>Site Header</header>
<main>
@RenderBody()
</main>
</body>
</html>
A section allows an individual view to provide content to a named region in the layout:
cshtml
@section Scripts {
<script src="/js/validation.js"></script>
}
The layout must define the section using @RenderSection.
The _ViewStart.cshtml file runs before each view in its folder hierarchy. It is commonly used to select the default layout:
cshtml
@{
Layout = "_Layout";
}
Together, layouts, sections, and ViewStart reduce duplication and provide a consistent visual structure.
Compare ViewBag, ViewData, and TempData in ASP.NET Core MVC. Mention their syntax, lifetime, and appropriate uses.
ViewBag:
- A dynamic property-based wrapper around
ViewData. - Uses simple syntax such as
ViewBag.Title = "Products". - Data is available during the current request.
- It is useful for small, optional values such as page titles or dropdown metadata.
ViewData:
- A dictionary based on string keys.
- Uses syntax such as
ViewData["Title"] = "Products". - Data is available during the current request and when rendering the selected view.
- It requires key names and often type casting when reading values.
TempData:
- Stores data for the current request and usually the next request.
- It is commonly used to display a one-time message after a redirect, such as a successful save notification.
- Example:
TempData["Message"] = "Record saved".
Comparison:
- ViewBag and ViewData are mainly used to pass supplementary data from a controller to a view.
- TempData is designed for short-lived data across redirects.
- Strongly typed view models are preferred for important or structured data because they provide compile-time checking and clearer contracts.
Explain the role of models and view models in ASP.NET Core MVC. Why should a view model sometimes be preferred over a domain model?
A model represents data and application behavior. It may be a domain entity, a data-transfer object, or a class used for form input.
A view model is a class designed specifically for a particular view or user interaction. It can combine properties from multiple domain objects and include presentation-specific or validation-specific information.
public class ProductEditViewModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(0.01, 100000)]
public decimal Price { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}Advantages of view models:
- Expose only the fields required by the view.
- Prevent accidental modification of protected domain properties.
- Support form-specific validation rules.
- Combine data from multiple sources.
- Keep the user interface independent from database entity structure.
- Make controller and view contracts explicit and strongly typed.
Using view models also reduces over-posting risks during model binding.
Explain session and state management in ASP.NET Core. Describe how session state is configured and used.
HTTP is stateless, so the server does not automatically remember information between requests. State management techniques maintain information across requests.
Session state stores user-specific data on the server while a session identifier is maintained in a cookie. Typical uses include shopping carts, temporary preferences, or multi-step workflows.
Configuration example:
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(20);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
app.UseSession();Usage:
HttpContext.Session.SetString("UserRole", "Editor");
string role = HttpContext.Session.GetString("UserRole");For complex values, JSON serialization can be used. In a multi-server deployment, a distributed session store such as a database or distributed cache is usually required. Session should not store large or sensitive data unnecessarily, and its use should comply with privacy and security requirements.
Describe the ASP.NET Core form-processing workflow from displaying a form to saving valid data.
The form-processing workflow normally follows the Post-Redirect-Get pattern.
- A
GETaction creates or retrieves a view model and returns the form view. - The Razor view uses form tag helpers and input tag helpers to generate the form controls.
- The user enters data and submits the form using an HTTP
POSTrequest. - Model binding maps form fields to the action parameter or view model.
- Server-side validation checks the model and populates
ModelState. - If validation fails, the controller returns the same view with the submitted values and validation messages.
- If validation succeeds, the controller performs the business operation and saves the data.
- The controller redirects to a
GETaction after a successful operation. - A success message may be stored in
TempDatafor display after the redirect.
This pattern avoids duplicate form submissions when a user refreshes the result page and keeps form display separate from form processing.
What is model binding in ASP.NET Core MVC? Explain the sources from which values are bound and discuss its benefits.
Model binding automatically converts incoming HTTP request data into action parameters or model objects.
For example:
[HttpPost]
public IActionResult Create(ProductCreateViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Index");
}The binder can obtain values from:
- Form fields in a
POSTrequest. - Route parameters such as
/products/12. - Query-string values such as
?category=books. - Request headers when explicitly configured.
- Uploaded files through
IFormFile. - Body content, especially in API controllers using formatters.
The binder performs type conversion, assigns matching property names, and creates nested objects or collections when possible. Binding attributes such as [FromRoute], [FromQuery], [FromForm], and [FromBody] can make the source explicit.
Model binding reduces repetitive parsing code, but input validation and authorization must still be performed.
Explain tag helpers in ASP.NET Core. Describe how form, input, label, validation-message, and anchor tag helpers are used.
Tag Helpers are server-side components that add server-generated behavior to HTML elements while preserving an HTML-like syntax.
Common examples include:
- Form tag helper: Generates the form action and can automatically include an antiforgery token for a
POSTform. - Input tag helper: Uses
asp-forto bind an input to a model property and generate suitable attributes such astype,name, andid. - Label tag helper: Uses
asp-forto generate a label associated with a model property. - Validation-message tag helper: Uses
asp-validation-forto display an error for one property. - Validation-summary tag helper: Displays model-level or all validation errors.
- Anchor tag helper: Uses attributes such as
asp-controller,asp-action, andasp-route-idto generate links.
Example:
cshtml
<form asp-action="Create" method="post">
<label asp-for="Name"></label>
<input asp-for="Name" />
<span asp-validation-for="Name"></span>
<button type="submit">Save</button>
</form>
Tag helpers reduce manual URL construction and help keep views synchronized with model metadata.
Explain server-side form validation in ASP.NET Core. Include data annotations, ModelState, and custom validation in your answer.
Server-side validation validates input on the server before business processing or database updates. It is essential because client-side validation can be bypassed.
Data annotations define common rules:
public class RegisterViewModel
{
[Required]
[StringLength(50)]
public string UserName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}ASP.NET Core evaluates these attributes during model binding and stores errors in ModelState.
if (!ModelState.IsValid)
{
return View(model);
}Custom validation can be implemented using IValidatableObject, a custom ValidationAttribute, or a validation service. A controller can add a business-rule error manually:
ModelState.AddModelError("Email", "This email is already registered.");The view displays errors using validation tag helpers. Server-side validation should cover required fields, formats, ranges, relationships between fields, authorization-related rules, and database constraints.
Explain client-side form validation in ASP.NET Core and compare it with server-side validation.
Client-side validation checks user input in the browser before the form is submitted. ASP.NET Core commonly supports it through unobtrusive validation, which uses HTML data-val-* attributes and JavaScript libraries such as jQuery Validation.
Typical setup:
- Include the validation JavaScript libraries.
- Use input and validation tag helpers in the Razor view.
- Apply validation attributes to the view model.
- Render validation messages with
asp-validation-fororasp-validation-summary.
The tag helpers convert model metadata into client-side validation attributes.
Comparison:
- Client-side validation gives immediate feedback and reduces unnecessary requests.
- Server-side validation is authoritative and protects the application when JavaScript is disabled or requests are maliciously altered.
- Client-side validation improves usability.
- Server-side validation protects data integrity and must always be performed before saving data.
The two forms of validation should use consistent rules where possible, but client-side validation must never replace server-side validation.
Compare different techniques for passing data from a controller to a view in ASP.NET Core MVC. Which technique is generally preferred and why?
ASP.NET Core MVC supports several data-passing techniques.
- View model: A strongly typed object passed through
return View(model). It is the preferred technique for primary page data because it provides type safety, discoverability, validation support, and clear contracts. - ViewBag: A dynamic property container suitable for small supplementary values. It does not provide compile-time checking.
- ViewData: A dictionary suitable for small supplementary values. It requires string keys and may require casting.
- TempData: Suitable for short-lived data that must survive a redirect, such as a notification message.
- Session: Suitable for user-specific data that must persist across multiple requests, but should not be used as a replacement for a view model.
- Razor layout data: Shared values can be provided through layout-specific mechanisms, but page-specific data should remain explicit.
A strongly typed view model is generally preferred because it makes the data contract visible, reduces runtime errors, limits exposed data, and separates presentation needs from domain entities.
Explain how an HTTP GET action and an HTTP POST action work together to implement a create operation in ASP.NET Core MVC.
A create operation commonly uses two actions with the same name but different HTTP verbs.
[HttpGet]
public IActionResult Create()
{
return View(new ProductCreateViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ProductCreateViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
productService.Create(model);
TempData["Message"] = "Product created successfully.";
return RedirectToAction(nameof(Index));
}The GET action displays an empty form and may populate lists or default values. The POST action receives submitted data through model binding, validates it, and saves it only when valid.
When validation fails, the POST action returns the same view so that errors and entered values can be shown. When it succeeds, it redirects to another GET action. The antiforgery attribute helps protect the operation against cross-site request forgery.
Describe the complete lifecycle of a submitted ASP.NET Core MVC form, including model binding, validation, action execution, and response generation.
The lifecycle of a submitted form consists of the following stages:
- The browser sends a
POSTrequest containing form fields, cookies, and the antiforgery token. - Routing selects the controller and action based on the URL and HTTP method.
- Authentication and authorization middleware evaluate the request.
- Model binding reads the submitted values and converts them into the action parameter type.
- Conversion errors and validation errors are recorded in
ModelState. - Data-annotation, custom, and business validation rules are evaluated.
- The controller checks
ModelState.IsValid. - For invalid input, the controller returns the view with the bound model and validation information.
- For valid input, the controller invokes a service or model operation to perform the required work.
- The action returns a result such as a view, redirect, JSON response, or error status.
- Razor renders HTML when a view result is selected.
- The response passes back through middleware and is returned to the browser.
This lifecycle separates transport concerns, validation, business processing, and presentation.
Distinguish between returning a View, RedirectToAction, Json, and HTTP status results from an ASP.NET Core controller action.
Controller actions return an IActionResult or a related result type. Different results communicate different intentions.
View()orView(model): Renders a Razor view, usually in response to a GET request or after invalid form input.RedirectToAction(): Sends an HTTP redirect to another action. It is commonly used after a successful POST to implement Post-Redirect-Get.Json()orJsonResult: Serializes an object into JSON, which is useful for AJAX requests or data endpoints.Ok()orOk(value): Returns a successful HTTP 200 response, commonly used by APIs.Created()orCreatedAtAction(): Indicates that a resource was created, usually with HTTP 201.BadRequest(): Indicates invalid request data, usually HTTP 400.Unauthorized()andForbid(): Indicate authentication or authorization problems.NotFound(): Indicates that the requested resource does not exist.
Choosing the correct result improves client behavior, accessibility, debugging, and adherence to HTTP semantics.
Explain how layouts and sections can be used to include page-specific JavaScript and CSS in an ASP.NET Core MVC application.
A layout contains the common structure shared by several views. It can define named sections for resources that are required only by particular pages.
Layout:
cshtml
<head>
<link rel="stylesheet" href="/css/site.css" />
@RenderSection("Styles", required: false)
</head>
<body>
@RenderBody()
@RenderSection("Scripts", required: false)
</body>
Individual view:
cshtml
@section Styles {
<link rel="stylesheet" href="/css/products.css" />
}
@section Scripts {
<script src="/js/products.js"></script>
}
@RenderSection determines where the content is inserted. Setting required: false allows views to omit the section. If a section is required and a view does not define it, Razor reports an error.
This approach keeps common resources in the layout while allowing individual pages to load only the scripts and styles they need.
Define ASP.NET Core and explain the major features that make it suitable for building modern web applications.
ASP.NET Core is an open-source, cross-platform framework developed by Microsoft for building web applications, web APIs, real-time applications, and backend services.
Major features:
- Cross-platform support: Applications can run on Windows, Linux, and macOS.
- High performance: It uses a lightweight and modular request-processing pipeline.
- Built-in dependency injection: Services can be registered and injected into controllers or other classes.
- Middleware-based architecture: Requests and responses can be processed through a configurable sequence of middleware components.
- Unified framework: The same framework supports MVC applications, Razor Pages, Web APIs, and SignalR applications.
- Environment-based configuration: Settings can be managed using files such as
appsettings.json, environment variables, and command-line arguments. - Integrated security: Authentication, authorization, HTTPS, and data-protection features are supported.
- Razor view engine: Dynamic HTML can be generated using Razor syntax.
- Cloud and container compatibility: Applications can be deployed easily to cloud platforms and containers.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →