4 Creating Asp Net Core Mvc Applications

NET Centric Computing · Unit 4 · 10 hrs

Creating ASP.NET core MVC applications

Exam-focused notes for Creating ASP.NET core MVC applications (NET Centric Computing, CSC378): what the TU syllabus asks and how it has actually been tested, with 9 solved past questions from this unit.

Creating ASP.NET core MVC applications in short

This unit builds an actual ASP.NET Core MVC application: the project's environment and startup, controllers and the action results they can return, rendering views with Razor, tag helpers, model binding and validation, URL routing, Web API controllers, and wiring dependencies together with the built-in dependency injection container.

Creating ASP.NET core MVC applications: notes

Setting up the Environment

By default, the wwwroot folder in an ASP.NET Core project is treated as the web root; static files such as JavaScript, CSS, and images should live in separate folders under it and are reachable with a relative path from the site's base URL, for example /css/app.css. The wwwroot folder can be renamed to something else, provided the new name is configured as the web root when the hosting environment is set up.

Every ASP.NET Core application configures itself through a Startup class, run when the application starts, which centres around two methods. ConfigureServices is where dependent classes are registered with the built-in dependency injection (IoC) container; once registered, a class can be requested anywhere in the application simply by including it as a constructor parameter, and the container injects it automatically. Configure is where the application's request processing pipeline is built, using the IApplicationBuilder instance the container supplies.

Controllers and Actions: Create Controllers, Create Actions and Action Results Types

A controller is the central unit that combines a Model with a View and returns the result to the user; it can also act alone for simple operations such as returning plain text or redirecting elsewhere. Controllers are conventionally placed in a folder named Controllers at the project root and named with a Controller suffix. A class qualifies as a controller if its name ends in "Controller", if it inherits from a class whose name ends in "Controller", or if it is decorated with the [Controller] attribute. Visual Studio offers two starting points when adding one, an MVC Controller or an API Controller; both derive from the same base controller class, and the practical difference is that an API controller is expected to return data in a serialized format rather than a rendered view.

Each public method on a controller is an action method: it can be invoked from the web through a URL, with routing responsible for matching an incoming request to the right action. Distinct action methods can share a name as long as they respond to different HTTP verbs, which is how an "Edit" action commonly has a GET version that renders the edit form and a POST version that saves the submitted data.

When an action finishes, it typically returns something that implements IActionResult. The common action result types are Content() (returns a plain string), View() (returns a rendered view), PartialView() (returns a partial view), File() (returns file content), Json() (returns a JSON response), and StatusCode() (returns a custom HTTP status code).

public class ProductController : Controller
{
    [HttpGet]
    public IActionResult Details(int id)
    {
        if (id <= 0)
        {
            return StatusCode(400);
        }

        return View();
    }
}

What this unit covers

  • Setting up the Environment
  • Controllers and Actions: Create Controllers, Create Actions and Action Results Types
  • Rendering HTML with Views: Razor Syntax
  • Understanding Tag Helpers
  • Models: Binding and Validations
  • URL Routing and features
  • Web API Applications: API Controllers, JSON
  • Dependency Injection and IOC containers

Controllers and Actions

2081 · 10 marks

How do you create controller? Illustrate with an example. Describe the procedure of rendering HTML with Razor with scenario.[10]

"Controller handles the user request. Typically the user uses the view, processes request and raises an HTTP request. Controller is the request handler." A Controller is a C class that: - Handles incoming HTTP requests - Interacts with the Model (data) - Returns a response (usually a View) --- St...

Open this answer on its own page →

2080 · 5 marks

How do you create controller? Mention some requirements for rendering HTML. [5]

A Controller is the central unit of an ASP.NET MVC application that combines the Model with a View and serves the result to the end-user. It handles user requests, executes application logic, builds a model, and returns the result in HTML, JSON, XML, or other formats. 1. Create a Class that Inher...

Open this answer on its own page →

Rendering HTML with Views

2081 · 5 marks

How does ASP.NET core MVC provides patterns-based way to build dynamic website? Explain. [5]

ASP.NET Core MVC is the Model-View-Controller application model that can be merged with the new ASP.NET Core. It is used to build dynamic websites as it provides fast development. ASP.NET MVC gives a powerful, patterns-based way to build dynamic websites that enables a clean separation of concern...

Open this answer on its own page →

Dependency Injection and IOC containers

2081 · 5 marks

Describe the life cycle of Dependency Injection container. [5]

Show solved answer

Life Cycle of Dependency Injection (DI) Container

In ASP.NET Core, the built-in IoC (Inversion of Control) container manages the creation and lifetime of service instances. The lifetime of a service defines how long an instance lives and when a new instance is created. There are three main service lifetimes:


1. Transient

  • The IoC container creates a new instance every time the service is requested.
  • Each call to resolve the service produces a fresh object.
  • Best suited for lightweight, stateless services.

Registration Example:

services.Add(new ServiceDescriptor(
    typeof(ILog),
    typeof(MyConsoleLogger),
    ServiceLifetime.Transient));

Use case: A simple utility/helper service that holds no shared state.


2. Scoped

  • The IoC container creates one instance per HTTP request and shares that same instance throughout the entire request.
  • Different requests get different instances.
  • Best suited for services that need to maintain state within a single request (e.g., database context).

Registration Example:

services.Add(new ServiceDescriptor(
    typeof(ILog),
    typeof(MyConsoleLogger),
    ServiceLifetime.Scoped));

Use case: A database context or unit-of-work that should be consistent within one request.


3. Singleton

  • The IoC container creates only one instance for the entire application lifetime.
  • The same instance is reused for every request and every user.
  • Best suited for services that are stateless and expensive to create, or that hold shared application-wide state.

Registration Example:

services.Add(new ServiceDescriptor(
    typeof(ILog),
    new MyConsoleLogger())); // single instance passed directly

Use case: A logging service or configuration service shared across the whole application.


Summary Table

LifetimeInstance CreatedShared Within
TransientEvery time requestedNot shared
ScopedOnce per HTTP requestSingle request
SingletonOnce per applicationEntire application

How Registration Works

Services are registered inside the ConfigureServices() method in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Singleton
    services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));

    // Transient
    services.Add(new ServiceDescriptor(typeof(ILog),
        typeof(MyConsoleLogger), ServiceLifetime.Transient));

    // Scoped
    services.Add(new ServiceDescriptor(typeof(ILog),
        typeof(MyConsoleLogger), ServiceLifetime.Scoped));
}

Once registered, the IoC container automatically injects the service via constructor injection wherever the service type is used as a constructor parameter, without the developer needing to manually instantiate it.

Open this answer on its own page →

2080 · 5 marks

Mention the two types of services managed by IoC container and how they are registered? [5]

Show solved answer

Two Types of Services Managed by IoC Container and Their Registration

Types of Services (Lifetimes)

The built-in IoC container in ASP.NET Core supports three kinds of service lifetimes, of which the two most commonly highlighted types are:


1. Singleton

  • The IoC container creates and shares a single instance of a service throughout the application's lifetime.
  • The instance is created the first time it is requested, and every subsequent request uses that same instance.
  • Suitable for services that maintain global state or are expensive to create.

2. Transient

  • The IoC container creates a new instance of the specified service type every time it is requested.
  • This lifetime works best for lightweight, stateless services.
  • Each request gets a completely fresh object.

3. Scoped (also managed by IoC)

  • The IoC container creates one instance per HTTP request.
  • The same instance is shared within a single request but a different instance is created for different requests.

How Services Are Registered

Services are registered inside the ConfigureServices method using the IServiceCollection interface. Registration is done using ServiceDescriptor:

public void ConfigureServices(IServiceCollection services)
{
    // Singleton registration
    services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));

    // Transient registration
    services.Add(new ServiceDescriptor(
        typeof(ILog),
        typeof(MyConsoleLogger),
        ServiceLifetime.Transient));

    // Scoped registration
    services.Add(new ServiceDescriptor(
        typeof(ILog),
        typeof(MyConsoleLogger),
        ServiceLifetime.Scoped));
}

Summary Table

LifetimeInstance CreatedShared?
SingletonOnce (first request)Across entire application
TransientEvery requestNot shared
ScopedOnce per HTTP requestWithin the same request only

Once registered, the IoC container automatically performs constructor injection wherever the service type is used as a constructor parameter.

Open this answer on its own page →

2079 · 5 marks

What does dependency injection and IOC container means? Explain. [5]

Dependency Injection is a design pattern used to achieve loose coupling between classes and their dependencies. Instead of a class creating its own dependencies (objects it needs), those dependencies are provided (injected) from outside the class, typically through a constructor, property, or met...

Open this answer on its own page →

Understanding Tag Helpers

2080 · 5 marks

What are tag helpers? What tag helper provides? [5]

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. Tag Helpers are authored in C and they target HTML elements based on: - The element name - The attribute name - The parent tag Tag Helpers are similar to HTML Helpers but provide a more natu...

Open this answer on its own page →

2079 · 5 marks

What is tag helper? Discuss about razor syntax with an example. [5]

Definition: Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. They are similar to HTML Helpers but follow a more natural HTML-like syntax. Key Points (from notes): - Tag Helpers are authored in C and target HTML elements based on element na...

Open this answer on its own page →

Setting up the Environment

2076 · 5 marks

What are the ASP requirements?[5]

ASP.NET (Active Server Pages .NET) is a web application framework developed by Microsoft for building dynamic web applications and services. To develop and run ASP.NET applications, the following requirements must be met: --- - ASP.NET applications require the .NET Framework or .NET Core (now .NE...

Open this answer on its own page →