Unit 3: Backend Development Using Asp.Net

INT402 — Modern Web Programming Tools And Techniques 10 min read

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.cs and 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: async and await improve 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 as HomeController, whose action methods receive requests.
  • Models/: Contains domain entities, data-transfer objects, and view models such as StudentViewModel.
  • Views/: Stores Razor views, normally grouped by controller; Views/Home/Index.cshtml serves HomeController.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 .csproj file declares the target framework, package references, and build settings.
  • Supporting folders: Properties/launchSettings.json defines local launch profiles, while bin/ and obj/ 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.
BASH
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.
CSHARP
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, Product may contain Id, Name, and Price.
  • View: A .cshtml template that renders HTML from data supplied by a controller.
  • Controller: Receives requests, invokes services or models, and returns an IActionResult.
  • Communication sequence:
    1. A browser requests /Products/Details/5.
    2. Routing selects ProductsController.Details(5).
    3. The controller obtains product 5 from a service.
    4. return View(product); passes the model to the view.
    5. Razor renders HTML, which is returned to the browser.
  • 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.
CSHARP
[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(), and File().
  • 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.Name outputs an encoded value.
  • Strongly typed view: @model ProductViewModel declares the type available through Model.
  • Code block: @{ ... } executes C# without directly producing output.
  • Control structure: Razor supports @if, @foreach, @for, and @switch.
CSHTML
@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, and asp-for generate 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.cshtml commonly 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.cshtml can assign a layout to all views beneath its directory.
CSHTML
@{
    Layout = "_Layout";
}
  • View imports: _ViewImports.cshtml centralizes 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: ViewData and ViewBag suit small items such as a page title or selection list.
  • Cross-request values: TempData supports 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.

  1. ViewData: A ViewDataDictionary accessed with string keys, for example ViewData["Title"] = "Products";.
  2. ViewBag: A dynamic wrapper over ViewData, for example ViewBag.Title = "Products";.
  • Shared storage: Setting ViewBag.Title makes the same value available through ViewData["Title"].
  • Type handling: Complex ViewData values may require casting; ViewBag defers 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.
  • Peek operation: TempData.Peek("Message") reads a value without marking it for deletion.
  • Keep operation: 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(), and UseSession().
CSHARP
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();

app.UseSession();
  • Storage operations: HttpContext.Session.SetString("UserName", "Asha") stores text, and GetString("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 category states 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 matching name and id attributes.
  • 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 Email binds to a parameter or property named Email.
  • Complex types: Indexed names such as Items[0].Name bind to collections.
  • Conversion errors: Invalid conversions, such as text supplied for an integer, create ModelState errors.
  • 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.

  1. Server-side validation: Data annotations are evaluated after model binding, and the action checks ModelState.IsValid.
  2. Client-side validation: Tag Helpers emit validation attributes interpreted by JavaScript validation libraries.
CSHARP
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, while asp-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.