Unit 3: Backend Development Using Asp.Net
I. Orientation
ASP.NET Core is Microsoft’s open-source, cross-platform framework for building web applications and HTTP APIs. It runs on modern .NET, uses a modular middleware pipeline, supports dependency injection, and commonly applies the Model-View-Controller pattern to separate application responsibilities.
- Cross-platform execution: Applications can run on Windows, Linux, and macOS through the .NET runtime.
- Request pipeline: Middleware components process each HTTP request in sequence and may pass it to the next component.
- Built-in dependency injection: Services are registered in
Program.csand supplied to controllers or other components through constructors. - Convention-based organization: MVC projects normally place models, views, and controllers in corresponding folders.
- Configuration system: Settings can come from
appsettings.json, environment variables, command-line arguments, and other providers. - Asynchronous processing:
asyncandawaitimprove scalability during database, file, and network operations. - Security support: The framework includes authentication, authorization, HTTPS redirection, antiforgery protection, and data-protection services.
II. Project Creation and Organization
An ASP.NET Core project combines source code, configuration, static resources, packages, and startup instructions into a deployable web application.
A. ASP.NET Core Project Folder Structure
The project structure separates application logic, presentation files, public assets, and configuration.
Controllers/: Contains controller classes such asHomeController, whose action methods receive requests.Models/: Contains domain entities, data-transfer objects, and view models such asStudentViewModel.Views/: Stores Razor views, normally grouped by controller;Views/Home/Index.cshtmlservesHomeController.Index.Views/Shared/: Holds reusable views, partial views, layouts, and validation components.wwwroot/: Contains publicly accessible static files such as CSS, JavaScript, fonts, and images.Program.cs: Registers services and configures the HTTP request pipeline.appsettings.json: Stores configuration such as logging levels and connection strings.- Project file: The
.csprojfile declares the target framework, package references, and build settings. - Supporting folders:
Properties/launchSettings.jsondefines local launch profiles, whilebin/andobj/contain generated build artifacts.
B. Building a Web Application using ASP.NET Core
Building an MVC application involves creating the project, registering MVC services, mapping routes, and implementing controllers and views.
- Project creation: The .NET CLI provides an MVC template.
dotnet new mvc -n CollegePortal
cd CollegePortal
dotnet run- Service registration:
AddControllersWithViews()adds the services required by controllers and Razor views. - Middleware configuration: Middleware is added in execution order.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();- Execution: Kestrel receives the HTTP request, routing selects an endpoint, and the selected controller action creates the response.
- Environment behavior: Development may display detailed errors, whereas production should use exception handling and secure transport.
III. MVC Architecture and Request Processing
MVC divides a web application into coordinated components, while routing and middleware connect incoming URLs to executable action methods.
A. Understanding MVC Pattern and Model-View-Controller Communication
The MVC pattern separates data and rules from request coordination and user-interface rendering.
- Model: Represents application data and business rules; for example,
Productmay containId,Name, andPrice. - View: A
.cshtmltemplate that renders HTML from data supplied by a controller. - Controller: Receives requests, invokes services or models, and returns an
IActionResult. - Communication sequence:
- A browser requests
/Products/Details/5. - Routing selects
ProductsController.Details(5). - The controller obtains product
5from a service. return View(product);passes the model to the view.- Razor renders HTML, which is returned to the browser.
- A browser requests
- Separation benefit: UI changes remain mainly in views, request logic in controllers, and business logic in models or services.
- Limitation: Placing database or business logic directly in controllers creates large, difficult-to-test controllers.
B. Handling Requests in .NET Core MVC Core
Request handling is the ordered process by which middleware, routing, model binding, and action execution produce an HTTP response.
- Middleware pipeline: Components may inspect, modify, terminate, or forward a request through
await next(context). - Routing: Conventional routing uses patterns, while attribute routing places templates directly on actions.
[HttpGet("products/{id:int}")]
public IActionResult Details(int id)
{
return View(_productService.Find(id));
}- HTTP method selection:
[HttpGet],[HttpPost],[HttpPut], and[HttpDelete]restrict actions to suitable request methods. - Action results: Common results include
View(),RedirectToAction(),NotFound(),BadRequest(),Json(), andFile(). - Action filters: Filters execute around authorization, action, result, or exception stages and support cross-cutting behavior.
- Asynchronous actions:
Task<IActionResult>avoids blocking a request thread while awaiting I/O.
IV. Razor-Based Presentation
Razor combines HTML with server-side C# and supports reusable page composition through layouts, sections, and shared startup conventions.
A. Razor View Engine and Razor Syntax
The Razor view engine processes .cshtml templates and converts model data and C# expressions into HTML responses.
- Code transition:
@moves from HTML into C#;@Model.Nameoutputs an encoded value. - Strongly typed view:
@model ProductViewModeldeclares the type available throughModel. - Code block:
@{ ... }executes C# without directly producing output. - Control structure: Razor supports
@if,@foreach,@for, and@switch.
@model ProductViewModel
<h2>@Model.Name</h2>
@if (Model.InStock)
{
<span>Available</span>
}- HTML encoding: Razor encodes normal expressions to reduce cross-site scripting risk; raw HTML should be emitted only from trusted content.
- Tag Helpers: Attributes such as
asp-controller,asp-action, andasp-forgenerate framework-aware HTML.
B. Layout, Sections and View Start
Layouts provide shared page structure, sections define optional content regions, and _ViewStart.cshtml applies common view settings.
- Layout:
_Layout.cshtmlcommonly contains the document structure, navigation, styles, and scripts. - Body placeholder:
@RenderBody()marks where each view’s main content is inserted. - Sections: A view declares
@section Scripts { ... }, while the layout uses@RenderSection("Scripts", required: false). - View start:
_ViewStart.cshtmlcan assign a layout to all views beneath its directory.
@{
Layout = "_Layout";
}- View imports:
_ViewImports.cshtmlcentralizes namespaces, model namespaces, and Tag Helper registrations. - Constraint: A section is available only to its immediate layout and must be rendered when declared as required.
V. Transferring Data and Maintaining State
ASP.NET Core offers several mechanisms for moving data between controllers, views, requests, and user sessions; each mechanism has a different lifetime.
A. Data Passing Techniques
Data may be passed through models, view-specific dictionaries, temporary storage, session state, route values, or query parameters.
- View models: Strongly typed classes are preferred for structured view data because compiler checking exposes property errors.
- View-only values:
ViewDataandViewBagsuit small items such as a page title or selection list. - Cross-request values:
TempDatasupports short-lived messages after a redirect. - Longer user state: Session stores server-side user data identified by a session cookie.
- Request inputs: Route values, query strings, form fields, and uploaded files can be bound to action parameters.
B. ViewBag and ViewData
ViewBag and ViewData transfer temporary data from a controller to the view during the same request.
- ViewData: A
ViewDataDictionaryaccessed with string keys, for exampleViewData["Title"] = "Products";. - ViewBag: A dynamic wrapper over
ViewData, for exampleViewBag.Title = "Products";.
- Shared storage: Setting
ViewBag.Titlemakes the same value available throughViewData["Title"]. - Type handling: Complex
ViewDatavalues may require casting;ViewBagdefers errors until runtime. - Scope: Values normally disappear when the current response ends.
- Recommendation: Use a strongly typed view model when the view depends on substantial or validated data.
C. Working with TempData
TempData preserves data until it is read by a later request, making it useful across redirects.
- Typical use: A POST action sets
TempData["Message"] = "Student saved";and redirects to an index action. - Provider: ASP.NET Core uses a cookie-based TempData provider by default; a session-state provider can also be configured.
- Read behavior: Reading a key marks it for deletion after the request.
Peekoperation:TempData.Peek("Message")reads a value without marking it for deletion.Keepoperation:TempData.Keep("Message")retains a previously read value for another request.- Constraint: TempData should hold small, short-lived values rather than sensitive or large object graphs.
D. Sessions and State Management
Session state stores per-user data across multiple requests because HTTP itself is stateless.
- Configuration: Session requires a distributed cache,
AddSession(), andUseSession().
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();
app.UseSession();- Storage operations:
HttpContext.Session.SetString("UserName", "Asha")stores text, andGetString("UserName")retrieves it. - Session identifier: A cookie holds an identifier; session data remains in the configured server-side store.
- Distributed deployment: Multi-server applications should use Redis, SQL Server, or another distributed cache.
- Other state methods: Cookies persist on the client, hidden fields travel with forms, and databases provide durable state.
- Security: Session must not be treated as permanent storage or as proof that a user is authorized.
E. Working with QueryString
A query string carries URL-encoded key-value data after ?, such as /Products?category=Books&page=2.
- Model binding: An action such as
Index(string category, int page = 1)automatically receives matching query values. - Explicit source:
[FromQuery] string categorystates that the value must come from the query string. - Multiple values: Repeated keys can bind to arrays or collections.
- Appropriate use: Queries suit filtering, searching, sorting, and pagination because URLs remain bookmarkable.
- Security limitation: Query values are visible in URLs, browser history, logs, and referrer data; secrets must not be placed there.
- Validation: Inputs remain untrusted and require range, format, and authorization checks.
VI. Forms, Binding, and Validation
ASP.NET Core forms collect user input, model binding converts that input into .NET objects, and validation checks whether the resulting data satisfies declared rules.
A. ASP.NET Core Forms
MVC forms use HTML or Tag Helpers to send fields to controller actions, usually through HTTP POST.
- Form generation:
<form asp-action="Create" method="post">generates the destination URL. - Field association:
<input asp-for="Name">produces matchingnameandidattributes. - Antiforgery protection: Form Tag Helpers generate a token that
[ValidateAntiForgeryToken]verifies. - POST/Redirect/GET: A successful POST should redirect to prevent duplicate submission during refresh.
- Failure path: Invalid forms should return the same view with the submitted model so values and validation messages remain visible.
B. Model Binding
Model binding converts request data into action parameters and complex model objects.
- Input sources: Values may come from form fields, route data, query strings, headers, or the request body.
- Name matching: A field named
Emailbinds to a parameter or property namedEmail. - Complex types: Indexed names such as
Items[0].Namebind to collections. - Conversion errors: Invalid conversions, such as text supplied for an integer, create
ModelStateerrors. - Binding control: Attributes including
[FromRoute],[FromQuery],[FromForm], and[FromBody]identify sources. - Security: Dedicated input models reduce over-posting by exposing only properties that users may modify.
C. Form Validations: Server Side and Client Side
Validation enforces model rules on the server and may mirror them in the browser for immediate feedback.
- Server-side validation: Data annotations are evaluated after model binding, and the action checks
ModelState.IsValid. - Client-side validation: Tag Helpers emit validation attributes interpreted by JavaScript validation libraries.
public class StudentInput
{
[Required]
[StringLength(50)]
public string Name { get; set; } = "";
[Range(16, 100)]
public int Age { get; set; }
}- Error display:
asp-validation-for="Name"shows a field error, whileasp-validation-summary="ModelOnly"shows model-level errors. - Authoritative layer: Server-side validation is mandatory because clients can disable or bypass JavaScript.
- Custom rules:
IValidatableObject, custom validation attributes, or service-level checks handle cross-field and business constraints. - Persistence rule: Data should be saved only after validation and business authorization both succeed.
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 →