Browse papers
A

Section A: Long Answer Questions

Attempt any TWO questions.

3 questions·10 marks each
1long10 marks

What is a Web API? Explain how to create a RESTful Web API in ASP.NET Core and consume it from a client.

Web API

A Web API (Application Programming Interface) is a service exposed over HTTP that allows clients (browsers, mobile apps, other servers) to communicate with a server-side application using standard HTTP verbs (GET, POST, PUT, DELETE) and data formats such as JSON or XML. It contains no UI; it only returns data, making it ideal for SPAs, mobile back-ends and service-to-service integration.

A RESTful Web API follows REST constraints: a uniform interface, statelessness, resource-based URIs (e.g. /api/products/5), and use of HTTP status codes (200, 201, 404, 500).

Creating a RESTful Web API in ASP.NET Core

1. Create the project

dotnet new webapi -n ProductApi

2. Define a model

public class Product {
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

3. Create an API controller (inherits ControllerBase, decorated with [ApiController] and [Route]):

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
    private static List<Product> _items = new();

    [HttpGet]
    public IEnumerable<Product> GetAll() => _items;

    [HttpGet("{id}")]
    public ActionResult<Product> Get(int id) {
        var p = _items.FirstOrDefault(x => x.Id == id);
        return p == null ? NotFound() : Ok(p);
    }

    [HttpPost]
    public ActionResult<Product> Create(Product p) {
        _items.Add(p);
        return CreatedAtAction(nameof(Get), new { id = p.Id }, p);
    }

    [HttpPut("{id}")]
    public IActionResult Update(int id, Product p) { /* update */ return NoContent(); }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id) { /* remove */ return NoContent(); }
}

4. Register services in Program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();

The framework automatically performs model binding, content negotiation (serialising to JSON), and routing.

Consuming the API from a client

Using HttpClient in a .NET client:

using var client = new HttpClient { BaseAddress = new Uri("https://localhost:5001/") };
// GET
List<Product> products =
    await client.GetFromJsonAsync<List<Product>>("api/products");
// POST
var resp = await client.PostAsJsonAsync("api/products",
              new Product { Id = 1, Name = "Pen", Price = 25 });
resp.EnsureSuccessStatusCode();

A JavaScript client can use fetch:

const res = await fetch('/api/products');
const data = await res.json();

Summary

  • A Web API exposes data over HTTP without UI.
  • ASP.NET Core builds REST APIs using [ApiController] controllers, attribute routing and automatic JSON serialisation.
  • Clients consume it via HttpClient (.NET) or fetch/axios (JS), handling responses by HTTP status codes.
web-apirest
2long10 marks

Explain Razor view engine. Discuss layouts, partial views, view components and tag helpers with examples.

Razor View Engine

Razor is the markup/templating engine used in ASP.NET Core MVC and Razor Pages to generate dynamic HTML. It mixes server-side C# code with HTML using the @ symbol. Files have the .cshtml extension and are compiled into C# classes at runtime/build time.

<h2>Hello @Model.Name</h2>
@if (Model.IsActive) { <p>Active user</p> }
@foreach (var item in Model.Items) { <li>@item</li> }

Key features: clean @ syntax, strong typing via @model, code blocks @{ ... }, and HTML encoding by default (preventing XSS).

Layouts

A layout (_Layout.cshtml) defines the common structure (header, nav, footer) shared by many views, avoiding duplication. The child view content is injected with @RenderBody().

<!-- _Layout.cshtml -->
<html><body>
  <header>My Site</header>
  @RenderBody()
  @RenderSection("Scripts", required: false)
</body></html>

Individual views set @{ Layout = "_Layout"; } (often centralised in _ViewStart.cshtml).

Partial Views

A partial view is a reusable .cshtml fragment (e.g. _ProductCard.cshtml) rendered inside other views, used for repeating UI such as a product card or comment block.

<partial name="_ProductCard" model="product" />
@* or *@ @await Html.PartialAsync("_ProductCard", product)

Partials only render markup; they do not run their own business logic.

View Components

A view component is like a mini-controller + partial view: it can contain logic (e.g. a database call) and returns a rendered fragment. Used for independent widgets such as a shopping cart summary or navigation menu.

public class CartSummary : ViewComponent {
    public IViewComponentResult Invoke() {
        var count = /* fetch from service */ 3;
        return View(count); // Views/Shared/Components/CartSummary/Default.cshtml
    }
}
<vc:cart-summary></vc:cart-summary>

Unlike partials, view components can have their own dependencies and do work.

Tag Helpers

Tag helpers are server-side components that let you create and render HTML elements using HTML-like syntax instead of @Html helpers, producing cleaner, designer-friendly markup.

<form asp-controller="Account" asp-action="Login">
  <input asp-for="Email" />
  <span asp-validation-for="Email"></span>
  <a asp-controller="Home" asp-action="Index">Home</a>
</form>

Common built-in tag helpers: asp-for, asp-action, asp-controller, asp-validation-for, and the anchor/form/input tag helpers. They are enabled with @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers (in _ViewImports.cshtml).

Summary Comparison

FeatureHas logic?Purpose
LayoutNoShared page structure
Partial viewNoReusable markup fragment
View componentYesSelf-contained widget with logic
Tag helperYes (server)HTML-friendly element generation
razorviews
3long10 marks

Describe the MVC design pattern. Explain the architecture and design principles of the ASP.NET Core framework with a diagram.

MVC Design Pattern

MVC (Model-View-Controller) is an architectural pattern that separates an application into three interconnected components, achieving separation of concerns, testability and parallel development.

  • Model — represents the application's data and business logic (e.g. domain classes, validation, database access). It is independent of the UI.
  • View — the presentation layer that renders the model as UI (HTML in web apps). It is passive and contains no business logic.
  • Controller — handles incoming requests, processes user input, interacts with the model, selects a view and returns a response. It acts as the coordinator.

Flow / Diagram (described)

        (1) HTTP Request
User ───────────────────────▶ Controller
  ▲                              │  (2) updates / queries
  │                              ▼
  │                            Model  ◀──▶ Database
  │                              │  (3) returns data
  │  (5) rendered response       ▼
  └──────────  View  ◀──────────┘ (4) controller selects view + passes model

The controller receives the request, asks the model for data, passes it to a view, and the view renders the output back to the user.

ASP.NET Core Architecture

ASP.NET Core is a cross-platform, open-source, high-performance framework for building web apps and APIs. Its architecture is centred on:

  • Kestrel web server — a lightweight cross-platform HTTP server hosting the app, often behind a reverse proxy (IIS/Nginx).
  • Middleware pipeline — request processing is a chain of middleware components (authentication, routing, static files, MVC, error handling). Each can short-circuit or pass to the next, configured in Program.cs.
  • Dependency Injection (DI) — a built-in IoC container registers services and injects them into controllers/components.
  • Routing — maps incoming URLs to controller actions (attribute or conventional routing).
  • Configuration — layered providers (appsettings.json, environment variables, command line).

Request pipeline (described)

Request ▶ [Kestrel] ▶ [Exception/HSTS] ▶ [Static Files] ▶ [Routing]
        ▶ [Authentication] ▶ [Authorization] ▶ [Endpoint/MVC] ▶ Response

Design Principles of ASP.NET Core

  1. Modularity — features come as small NuGet packages added only as needed.
  2. Dependency Injection first-class — loose coupling and testability.
  3. Middleware-based, composable pipeline — each concern is a separate component.
  4. Cross-platform & cloud-ready — runs on Windows, Linux, macOS, containers.
  5. Convention over configuration with the option to override.
  6. Unified MVC + Web API + Razor Pages programming model.

Summary

MVC cleanly separates data (Model), presentation (View) and request handling (Controller). ASP.NET Core implements this on a modular, DI-driven, middleware pipeline hosted by Kestrel, giving a cross-platform, testable and high-performance web framework.

mvcaspnet-core
B

Section B: Short Answer Questions

Attempt any EIGHT questions.

9 questions·5 marks each
4short5 marks

Differentiate between struct and enum in C#.

struct vs enum in C#

Aspectstructenum
PurposeA value type that groups related data and behaviour (fields, methods, properties, constructors).A value type that defines a set of named integral constants.
MembersCan hold multiple fields of different types, plus methods.Holds a fixed list of named values only.
Underlying typeComposite (user-defined layout).Backed by an integral type (default int; can be byte, long, etc.).
Examplestruct Point { public int X, Y; }enum Day { Mon, Tue, Wed }
UsageLightweight objects like coordinates, money.Fixed options like days, states, status codes.
MethodsCan contain methods/constructors.Cannot contain methods (only named constants).
struct Point { public int X; public int Y; }
enum Day { Sunday, Monday, Tuesday }

Both are value types (stored on the stack / inline), but a struct models a composite data structure with behaviour, whereas an enum simply names a set of constant values.

csharp
5short5 marks

Explain exception handling in C# with an example.

Exception Handling in C#

An exception is a runtime error that disrupts normal program flow (e.g. dividing by zero, accessing a null object, file not found). C# handles exceptions using the try-catch-finally construct, which prevents the program from crashing and lets it recover gracefully.

  • try — encloses code that may throw an exception.
  • catch — handles a specific exception type; multiple catch blocks can be chained.
  • finally — always executes (whether or not an exception occurred), used for cleanup such as closing files.
  • throw — raises an exception explicitly.

Example

try
{
    int a = 10, b = 0;
    int result = a / b;          // throws DivideByZeroException
    Console.WriteLine(result);
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero: " + ex.Message);
}
catch (Exception ex)             // general fallback
{
    Console.WriteLine("Error: " + ex.Message);
}
finally
{
    Console.WriteLine("Execution completed.");
}

Output:

Cannot divide by zero: Attempted to divide by zero.
Execution completed.

All exception classes derive from System.Exception. Catching the most specific exception first and using finally for cleanup are best practices.

csharpexception-handling
6short5 marks

Differentiate between Entity Framework and ADO.NET.

Entity Framework (EF) vs ADO.NET

AspectEntity FrameworkADO.NET
TypeORM (Object-Relational Mapper) built on top of ADO.NET.Low-level data access technology.
AbstractionHigh — works with C# objects/entities; SQL is auto-generated.Low — developer writes raw SQL queries and commands.
QueryingLINQ to Entities (context.Students.Where(...)).SQL strings with SqlCommand, SqlDataReader, DataSet.
ProductivityFaster development, less boilerplate, change tracking, migrations.More code to write and maintain.
PerformanceSlight overhead from mapping/translation.Faster and more lightweight (direct access).
ControlLess fine-grained control over SQL.Full control over the exact SQL executed.
MappingAutomatic object-to-table mapping.Manual mapping between rows and objects.
// EF
var students = context.Students.Where(s => s.Age > 18).ToList();

// ADO.NET
var cmd = new SqlCommand("SELECT * FROM Students WHERE Age > 18", conn);
var reader = cmd.ExecuteReader();

In short: ADO.NET gives raw, high-performance, manual database access, while Entity Framework is a productivity-focused ORM layer on top of it that maps tables to objects and auto-generates SQL.

entity-framework
7short5 marks

Explain the procedure to build, run and deploy an ASP.NET Core application.

Building, Running and Deploying an ASP.NET Core Application

1. Build

The build step compiles the source code and dependencies into assemblies (.dll).

dotnet build              # compiles the project (Debug by default)
dotnet build -c Release   # optimized build

This restores NuGet packages and produces output in the bin/ folder.

2. Run

The run step launches the app on the Kestrel server (default ports such as 5000/5001).

dotnet run

Visual Studio / VS Code can also run with debugging (F5). The app is then accessible via the browser.

3. Publish

The publish step packages the app and all required files for deployment into a single folder.

dotnet publish -c Release -o ./publish

Two deployment modes:

  • Framework-dependent — needs the .NET runtime installed on the target.
  • Self-contained — bundles the runtime (--self-contained -r win-x64).

4. Deploy

The published output is hosted on a server. Common options:

  • IIS (Windows) using the ASP.NET Core Module behind IIS as reverse proxy.
  • Kestrel behind Nginx/Apache on Linux.
  • Azure App Service (az webapp or VS publish).
  • Docker container for cross-platform deployment.
FROM mcr.microsoft.com/dotnet/aspnet:8.0
COPY ./publish /app
WORKDIR /app
ENTRYPOINT ["dotnet", "MyApp.dll"]

Summary

Build (dotnet build) → Run/test (dotnet run) → Publish (dotnet publish) → Deploy to IIS, Nginx/Kestrel, Azure or Docker.

aspnet-coredeployment
8short5 marks

What are validation controls? Explain client-side validation in ASP.NET Core.

Validation Controls

Validation ensures that user-supplied data is correct, complete and safe before it is processed or stored. In ASP.NET Core, validation is primarily model-based using Data Annotation attributes applied to model properties.

public class RegisterModel {
    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    [EmailAddress]
    public string Email { get; set; }

    [Range(18, 60)]
    public int Age { get; set; }

    [StringLength(20, MinimumLength = 6)]
    public string Password { get; set; }
}

Common attributes: [Required], [StringLength], [Range], [EmailAddress], [RegularExpression], [Compare].

Client-Side Validation

Client-side validation runs in the browser before the form is submitted, giving instant feedback and reducing round-trips to the server. ASP.NET Core enables it automatically by combining:

  • Tag helpers asp-for and asp-validation-for, which emit HTML5 data-val-* attributes from the model's data annotations.
  • jQuery Unobtrusive Validation (jquery.validate.js + jquery.validate.unobtrusive.js), which reads those attributes and validates without inline script.
<form asp-action="Register">
    <input asp-for="Email" />
    <span asp-validation-for="Email"></span>
    <button type="submit">Register</button>
</form>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}

Note: client-side validation improves user experience but is not a security boundary — the same rules are re-checked on the server via ModelState.IsValid, since clients can bypass JavaScript.

validation
9short5 marks

Explain the role of the appsettings.json and configuration in ASP.NET Core.

Role of appsettings.json and Configuration in ASP.NET Core

appsettings.json is the default JSON configuration file in an ASP.NET Core application. It stores application settings such as connection strings, logging levels, API keys and custom options outside the compiled code, so they can be changed without rebuilding.

{
  "ConnectionStrings": {
    "Default": "Server=.;Database=Shop;Trusted_Connection=True;"
  },
  "Logging": { "LogLevel": { "Default": "Information" } },
  "AppSettings": { "SiteName": "MyShop", "PageSize": 10 }
}

Configuration System

ASP.NET Core has a layered configuration provider model. Sources are read in order, and later sources override earlier ones:

  1. appsettings.json
  2. appsettings.{Environment}.json (e.g. appsettings.Development.json)
  3. User secrets (development)
  4. Environment variables
  5. Command-line arguments

This enables different settings per environment (Development/Production).

Accessing configuration

Values are read through the injected IConfiguration:

string conn = builder.Configuration.GetConnectionString("Default");
string site = builder.Configuration["AppSettings:SiteName"];

Strongly-typed binding (the Options pattern):

builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("AppSettings"));
// inject IOptions<AppSettings> where needed

Summary

appsettings.json externalises configuration data; the configuration system layers multiple providers, supports environment-specific overrides, and exposes values via IConfiguration or the strongly-typed Options pattern.

configuration
10short5 marks

What is a ViewModel? How does it differ from a model?

ViewModel

A ViewModel is a class designed specifically to carry exactly the data a view needs for display, shaped for presentation rather than for the database. It can combine fields from several models, add display-only properties, and exclude data the view should not see.

public class ProductDetailsViewModel {
    public string ProductName { get; set; }
    public decimal Price { get; set; }
    public string CategoryName { get; set; }   // from another model
    public List<string> Reviews { get; set; }
    public bool IsOnSale { get; set; }          // computed for the view
}

ViewModel vs Model

AspectModelViewModel
PurposeRepresents domain/business data and maps to the database.Represents data tailored for a specific view/UI.
ScopeMirrors a single entity/table.Can aggregate data from multiple models.
ContentsAll entity fields, business logic.Only fields needed by the view + display helpers.
CouplingTied to persistence layer.Tied to the presentation layer.
SecurityMay expose sensitive fields.Exposes only safe, required fields (prevents over-posting).

In short: a model describes the application's underlying data, while a ViewModel is a presentation-specific container that gathers and reshapes exactly the data a view needs, improving separation of concerns and security.

mvcviewmodel
11short5 marks

Explain the Startup class and the Program.cs in ASP.NET Core.

Program.cs and the Startup Class in ASP.NET Core

Program.cs

Program.cs is the entry point of an ASP.NET Core application. It creates and configures the host, registers services, builds the request (middleware) pipeline and runs the app. In .NET 6+ it uses the simplified minimal hosting model that merges the old Program and Startup responsibilities into one file.

var builder = WebApplication.CreateBuilder(args);

// --- Service registration (the old ConfigureServices) ---
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<AppDbContext>();

var app = builder.Build();

// --- Middleware pipeline (the old Configure) ---
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");

app.Run();

Startup Class (pre-.NET 6 style)

In earlier versions, configuration lived in a separate Startup class with two key methods:

  • ConfigureServices(IServiceCollection services) — registers services into the DI container (e.g. MVC, EF Core, authentication).
  • Configure(IApplicationBuilder app, IWebHostEnvironment env) — defines the middleware pipeline (order matters: static files → routing → auth → endpoints).
public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        services.AddControllersWithViews();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
        app.UseRouting();
        app.UseEndpoints(e => e.MapDefaultControllerRoute());
    }
}

Summary

Program.cs is the application's entry point and host bootstrapper. The Startup class (or its merged equivalent in modern Program.cs) splits configuration into service registration (DI) and middleware pipeline setup. From .NET 6 onward both are combined into a single streamlined Program.cs.

aspnet-core
12short5 marks

What are tag helpers? Give two examples.

Tag Helpers

Tag helpers are server-side components in ASP.NET Core that enable server-side code to participate in creating and rendering HTML elements in Razor views. They let developers write HTML-like, designer-friendly markup (attributes prefixed with asp-) instead of using older @Html.* helper methods, while still generating the correct HTML, URLs and validation attributes on the server.

They are enabled in _ViewImports.cshtml:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Two Examples

1. Anchor Tag Helper (asp-controller, asp-action) — generates a correct URL from routing instead of a hard-coded link:

<a asp-controller="Home" asp-action="Index">Home</a>
<!-- renders: <a href="/Home/Index">Home</a> -->

2. Input / Form Tag Helper (asp-for) — binds an input to a model property and emits the right name, id, value and validation attributes:

<form asp-action="Register">
    <input asp-for="Email" />
    <span asp-validation-for="Email"></span>
</form>
<!-- <input> gets name="Email" plus data-val attributes -->

Other common tag helpers include asp-validation-for, asp-route-*, the <environment> tag helper, and the <label asp-for> tag helper.

Benefit: cleaner, more maintainable, IntelliSense-friendly markup that keeps strong typing and routing intact.

razor

Frequently asked questions

Where can I find the BSc CSIT (TU) NET Centric Computing (BSc CSIT, CSC367) question paper 2081?
The full BSc CSIT (TU) NET Centric Computing (BSc CSIT, CSC367) 2081 (regular) question paper is available free on Kekkei. You can read every question online and attempt the paper under timed exam conditions.
Does the NET Centric Computing (BSc CSIT, CSC367) 2081 paper come with solutions?
Yes. Every question on this NET Centric Computing (BSc CSIT, CSC367) past paper includes a step-by-step solution, plus instant AI feedback when you attempt it on Kekkei.
How many marks is the BSc CSIT (TU) NET Centric Computing (BSc CSIT, CSC367) 2081 paper?
The BSc CSIT (TU) NET Centric Computing (BSc CSIT, CSC367) 2081 paper carries 60 full marks and is meant to be completed in 180 minutes, across 12 questions.
Is practising this NET Centric Computing (BSc CSIT, CSC367) past paper free?
Yes — reading and attempting this NET Centric Computing (BSc CSIT, CSC367) past paper on Kekkei is completely free.