WorksheetsKAPITTEL 1: ASP.NET Core MVC - grunnleggende
Total questions: 125
Worksheet time: 1hrs 3mins
In MVC, which component is responsible for rendering HTML to the client?
Model classes holding data
Repository layer abstractions
View component using .cshtml
Controller methods orchestrating
Which folder typically contains classes like Obstacle, Report, User, and Organization as core domain entities?
Views folder for Razor
Models folder for DTOs
Domain folder for main models
Services folder for business
What is the primary responsibility of Controllers in an ASP.NET Core MVC project?
Handle requests and route logic
Serve static client scripts
Render Razor HTML views
Persist data to database
Which Program.cs setup step enables constructor injection of app services throughout the app?
Register services for DI
Configure Identity auth
Set database connections
Define endpoint routing
Which routing pattern represents the conventional route template in ASP.NET Core MVC?
{controller}/{action}/{id?}
/api/{resource}/{id}
/{area}/{page}/{id}
/v1/{entity}/{verb}
Which statement about GET actions is accurate in MVC controllers?
Send data and modify state
Require anti-forgery token
Cannot be cached at all
Retrieve data without changes
Which attribute is commonly applied to secure POST actions against CSRF?
AllowAnonymous attribute
ValidateAntiForgeryToken attribute
Authorize attribute only
ResponseCache attribute
Which service layer folder would likely include UserService and OrganizationService implementations?
Services containing business logic
Repository for EF Core access
DataContext for connections
Views for Razor pages
When integrating a map feature using JavaScript and Leaflet, which approach correctly sends user interactions to the server?
AJAX requests from map.js
Form posts from Razor only
WebSockets by default
Static JSON files export
Which statement best characterizes the GET method in ASP.NET Core MVC?
Requires anti-forgery validation
Fetches data without side effects
Returns different results for same URL
Submits data and changes state
In a controller, which attribute should decorate an action that processes a form submission to create a record?
[Route] attribute
[HttpGet] attribute
[HttpPost] attribute
[Authorize] attribute
A page displays product details using the same URL across requests. Which behavior aligns with best practice for that endpoint?
Require anti-forgery token on each request
Disable caching to prevent stale content
Modify database on each view request
Allow response caching for identical queries
Which scenario most clearly requires an anti-forgery token in ASP.NET Core MVC?
Submitting a profile update form
Navigating to a read-only dashboard
Loading a list of products
Fetching static assets like CSS
You must design an order submission endpoint. Which choice reflects safe, cache behavior and data impact?
GET: safe, cacheable, no data change
POST: safe, cacheable, no data change
GET: unsafe, not cacheable, changes data
POST: may change data, not cacheable, needs CSRF protection
Which library is commonly used to render interactive maps in a client-side map.js for an ASP.NET Core MVC app?
Dapper micro-ORM utilities
Bootstrap responsive styling
SignalR real-time messaging
Leaflet library for web maps
What is the primary purpose of making an AJAX request from map.js when a user adds a marker?
Send marker data to server asynchronously
Render server-side Razor view template
Generate anti-forgery token automatically
Invalidate all user session entries
In the draft submission workflow, what should happen immediately after loading the draft from session?
Validate the model for consistency
Remove the draft from the session
Attach obstacles to the report
Create a new database report
Which statement best describes session usage for map-related drafts?
Temporarily store draft before database
Permanently persist data across servers
Encrypt Razor views during rendering
Cache static files for faster delivery
A form in an ASP.NET Core MVC Razor view needs CSRF protection. Which element provides the required token?
Html.AntiForgeryToken helper
Leaflet initialization code
AJAX GET request header
Session.Remove on draft key
You are implementing SubmitDraft in a controller. Which ordered step correctly comes after fetching the logged-in user?
Create the report entity next
Validate the draft model
Delete the draft from session
Initialize the Leaflet map
Why should POST requests that finalize a draft not be cached by clients or proxies?
They modify server-side state
They include large map tiles
They are always unauthenticated
They return identical responses
When retrieving a saved draft from session, which API correctly deserializes a typed object?
TempData.Peek
HttpContext.Request.Query.TryGetValue
HttpContext.Session.Get
ViewData.GetModel
Which statement best describes Entity Framework Core in an ASP.NET Core MVC application?
It is a caching layer for session storage
It is a frontend library for UI rendering
It is a NoSQL engine replacing SQL Server
It is an ORM translating objects to tables
In a solution using ApplicationContext and AuthDbContext, what is the primary responsibility of AuthDbContext?
Handling view rendering and layouts
Configuring client-side routing
Storing obstacles and reports
Managing users, roles, organizations
What EF Core set represents a table for obstacles in the database?
DbSet
List
IEnumerable
ObservableCollection
Which method pair is the correct sequence to persist a new entity with EF Core?
ToListAsync then Include
Where then FirstOrDefaultAsync
SaveChangesAsync then AddAsync
AddAsync then SaveChangesAsync
Choose the statement that explains OnModelCreating in EF Core.
Handles HTTP routing and endpoints
Defines keys, relationships, seed data
Generates antiforgery tokens for forms
Executes client-side validations only
A developer needs related Report data when querying Obstacles. Which API usage achieves this?
Include(o => o.Report) on the query
Select new Report from context
Join Reports using raw SQL strings
Load all tables and filter in memory
Why are parameterized queries important when EF Core translates LINQ to SQL?
They protect against SQL injection attacks
They improve client-side rendering speed
They disable migrations by default
They enforce MVC controller naming
When is ExecuteSqlRaw appropriate in this architecture?
Only for migration handling, not user data
For caching session state across requests
For every data read to improve speed
For building views and controllers
Which statement best describes how Entity Framework Core handles SQL when using LINQ queries?
It auto-generates parameterized SQL from LINQ
It requires manual SQL strings for every query
It only supports raw SQL without parameters
It compiles LINQ to non-parameterized SQL
You need to fetch all rows from the Obstacles table using EF Core. Which LINQ call aligns with the SQL produced?
_context.Obstacles.RemoveRange() → SELECT * FROM Obstacles
_context.Obstacles.ToListAsync() → SELECT * FROM Obstacles
_context.Obstacles.FindAsync() → SELECT * FROM Obstacles
_context.Obstacles.Update() → SELECT * FROM Obstacles
A query must filter by Id using user input while preventing SQL injection. Which EF Core pattern achieves this?
ExecuteSqlRaw with user-supplied id
Build dynamic SQL via string.Format
Concatenate id into a SQL string
Where(o => o.Id == id) uses parameters
When is ExecuteSqlRaw appropriate in an ASP.NET Core app that uses EF Core?
For joining related tables in LINQ
For everyday queries with user input
For replacing all LINQ queries in production
For migration or admin scripts without user data
Which statement best defines the Repository Pattern in ASP.NET Core MVC?
An abstraction layer for data access operations
A class exposing database tables directly
A configuration file storing connection strings
A UI component rendering controller views
In a typical implementation, what does a controller depend on when using the Repository Pattern?
Concrete repository class directly
Static helper for SQL queries
Entity Framework DbContext instance
Repository interface such as IObstacleRepository
Which benefit most directly supports unit testing when applying the Repository Pattern?
Stronger runtime type safety
Ability to mock the repository interface
Automatic query optimization features
Reduced need for dependency injection
Choose the primary purpose of database abstraction provided by a repository.
Replace controllers with service singletons
Expose how the data is fetched internally
Generate SQL scripts for migrations
Hide data access details behind an interface
You need to switch from SQL Server to PostgreSQL without changing controller code. Which approach aligns with the Repository Pattern?
Swap the concrete repository implementing the interface
Embed raw SQL strings inside each controller
Use a static global DbContext shared everywhere
Modify all controller actions to new queries
A team wants more maintainable code and reuse across features. Which Repository Pattern characteristic addresses this goal?
Queries scattered through UI components
Interfaces removed to simplify design
Repositories encapsulate CRUD operations
Controllers own data retrieval logic
Which statement best describes Dependency Injection in ASP.NET Core MVC?
Classes create their own required objects
Services are only available as singletons
A system provides required objects to classes
Controllers directly instantiate repository classes
What is the primary purpose of registering a service with AddScoped in Program.cs?
Create one instance for the entire application
Create a new instance for each dependency resolution
Create a new instance per controller method
Create one instance per HTTP request scope
Given an interface IObstacleRepository and class ObstacleRepository, how should the controller receive this dependency?
Resolve ObstacleRepository using ServiceLocator in the action
Inject IObstacleRepository via the controller constructor
Use a static field to hold the repository
Instantiate ObstacleRepository inside each action
Which Program.cs registration correctly binds an interface to its implementation as scoped?
builder.Services.AddScoped
builder.Services.AddScoped
builder.Services.AddTransient
builder.Services.AddSingleton
Why does using interfaces with DI improve testability in controllers?
Interfaces allow mocking of dependencies
Interfaces force runtime compilation
Interfaces reduce the number of controller actions
Interfaces eliminate the need for service registration
What is the primary purpose of authentication in an ASP.NET Core MVC app?
Log performance metrics only
Encrypt all traffic globally
Grant permissions to data
Verify user identity claims
Which ASP.NET Core component typically handles user sign-in and identity verification?
ASP.NET Core Identity
Entity Framework Core
Razor View Engine
Kestrel Web Server
Arrange the typical login flow: user submits credentials, system validates, cookie issued, user considered signed in. Which step occurs immediately after validation succeeds?
Authentication cookie is created
Password is rehashed again
Session state is abandoned
Two-factor is disabled globally
During password sign-in, which API commonly checks the provided username and password?
SignInManager.PasswordSignInAsync
HttpContext.SignOutAsync
UserManager.AddToRoleAsync
DbContext.SaveChangesAsync
Which combination of cookie flags helps reduce theft or misuse of authentication cookies?
HttpOnly, Secure, SameSite
Unsigned, Plain, CrossSite
Persistent, Large, PathWide
Readable, Shared, AnyOrigin
A strong password policy is configured with minimum length and character diversity. Which set best matches typical complexity requirements?
At least 4 characters any printable characters
At least 10 letters all lowercase only
Exactly 6 digits only with no letters
At least 6 characters, uppercase and lowercase, digits and symbols
A user logs in successfully. What does the authentication cookie represent for subsequent requests?
A compiled Razor view cache
Proof the user is signed in
An encryption key for files
A database connection string
What is the primary purpose of authorization in an ASP.NET Core MVC app?
Validate password complexity requirements
Verify identity during sign-in
Determine what actions a user may perform
Encrypt cookies for secure storage
Which attribute restricts a controller action to users in specified roles?
[RequireHttps] attribute on actions
[AllowAnonymous] attribute usage
[Authorize] attribute with Roles
[ValidateAntiForgeryToken] attribute
Given roles SuperAdmin, Registrar, and FlightCrew, which role should approve or reject incident barriers?
No role can approve or reject
FlightCrew approves and rejects only
Registrar handles approve or reject
SuperAdmin manages every feature
You need an action accessible to both Registrar and SuperAdmin. Which configuration fits best?
[Authorize(Roles="Registrar,SuperAdmin")] on action
[Authorize] without any roles specified
User.IsInRole("FlightCrew") check only
DenyAnonymousUsers middleware usage
A page must be visible only to SuperAdmin. What is the simplest implementation approach?
Check User.IsInRole in Razor view
Add role to cookie manually
Apply [Authorize(Roles="SuperAdmin")]
Hide the link in navigation only
During runtime, you must branch logic if the current user is SuperAdmin. What code-level check should you use?
User.IsInRole("SuperAdmin") condition
IOptions
HttpContext.SignInManager method call
ModelState.IsValid boolean check
Where are application roles typically defined when using ASP.NET Core Identity with Entity Framework Core?
Stored in appsettings.json only
Hardcoded in controller constructors
In AuthDbContext via model configuration
Inside Startup.cs Configure method
What is the primary purpose of seed data for roles in an ASP.NET Core Identity setup?
Generate cookies for sign-in
Encrypt role names for storage
Log failed role assignments
Create initial roles at deployment
During user registration, how are roles usually assigned in an Identity-based MVC application?
Never assigned automatically
Manually via SQL after deployment
Only after first successful login
Assigned at registration workflow
Which statement best differentiates public registration versus admin registration in a role‑based system?
Neither requires any approval process
Public users auto‑approved; admins need review
Public users need approval; admins auto‑approved
Both require manual approval by staff
Which organizational roles are most likely included for an aviation obstacle management system using ASP.NET Core Identity?
Sales, Marketing, HR assistants
Drivers, Gardeners, Warehouse staff
Teachers, Students, Librarians
Kartverket, Police, Norwegian Air Force
You are designing authorization filters for controllers. Which attribute correctly restricts an action to SuperAdmin only while keeping code maintainable?
Checking User.IsInRole in every action
Using HttpContext.Items for flags
[Authorize(Roles="SuperAdmin")] attribute
Hiding links in Razor views only
Which statement best defines SQL Injection in web applications?
An attacker forces the server to run their SQL
A user optimizes queries for faster performance
A database compresses data to save storage
An administrator schedules maintenance tasks
Which example illustrates a SQL Injection payload appended to input?
5; DROP TABLE Obstacles;
WHERE Id = @id parameter
SELECT * FROM Obstacles
CREATE INDEX ON Obstacles
Why do parameterized queries mitigate SQL Injection risks?
ORMs block all write operations by default
Indexes automatically validate user input
Queries are always encrypted at rest
Values are bound as parameters, not concatenated
In Entity Framework Core, which LINQ query is considered safe against injection when filtering by Id?
SELECT Obstacles FROM context without WHERE
_context.Database.ExecuteSqlRaw("SELECT * FROM Obstacles")
$"SELECT * FROM Obstacles WHERE Id = {id}"
_context.Obstacles.Where(o => o.Id == id)
When EF Core translates a safe LINQ filter by Id, which SQL form does it generate?
SELECT * FROM Obstacles WHERE Id = id
SELECT * FROM Obstacles WHERE Id LIKE id%
SELECT * FROM Obstacles WHERE Id = @id
SELECT * FROM Obstacles WHERE Id = 'id'
Which statement best defines CSRF in web applications?
A method to encrypt sensitive cookies
A bug causing server-side crashes
A header blocking third-party scripts
An attack forging cross-site requests
In a CSRF attack, what does the attacker typically achieve?
Inject executable JavaScript into views
Steal database credentials directly
Trigger actions without the user's awareness
Bypass TLS and downgrade HTTPS
What primary mechanism mitigates CSRF in ASP.NET Core MVC?
SQL parameterization
CORS preflight checks
X-Content-Type-Options
Anti-forgery tokens
Where is the anti-forgery token usually generated in an ASP.NET Core app?
By the CDN caching layer
In the browser via client script
On the server during form rendering
Inside the database engine
When must the anti-forgery token be included to validate a state-changing request?
With POST requests to protected endpoints
Only with GET requests for pages
Only when cookies are disabled
With any request using HTTP/2
Which attribute enforces token validation on MVC POST actions?
ProducesResponseType
RequireHttps
Authorize
ValidateAntiForgeryToken
How can JavaScript send the anti-forgery token during AJAX calls in ASP.NET Core?
Store the token inside localStorage only
Send cookies without any token
Disable validation for AJAX endpoints
Read the token and add it to the request
Which statement best defines Cross-Site Scripting (XSS) in web applications?
Stealing cookies via insecure HTTPS channels
Exploiting SQL queries through user input
Bypassing server-side input validation checks
Injecting malicious JavaScript into a site
In Razor Views, what primary defense reduces XSS risk when rendering user-provided content?
Blocking cookies for authenticated users
Manual URL encoding for all links
Automatic HTML escaping of output
Disabling JavaScript in the browser
Which HTTP response header defines allowed script sources to mitigate XSS?
X-Frame-Options header
Content-Security-Policy (CSP) header
X-Content-Type-Options header
X-XSS-Protection header
A site returns the header: X-XSS-Protection: 1; mode=block. What does this primarily instruct compatible browsers to do?
Force HTTPS for all external resources
Disable all inline styles and fonts
Enable built-in XSS filters and block attacks
Prevent MIME type sniffing for scripts
You must design a three-layer XSS defense for an MVC app. Which combination aligns with a layered approach?
SQL parameterization, CSP policy, gzip
Razor escaping, CSP policy, X-XSS-Protection
Server caching, CDN, HTTP keep-alive
Cookie flags, CORS headers, CSP
Given CSP: default-src 'self'; script-src 'self', which behavior is most accurate?
Inline JavaScript executes without restriction
Scripts load only from the same origin
Images can load from any external domain
Stylesheets must come from data URLs
Which statement best describes unit testing in an ASP.NET Core MVC solution?
Tests isolated single components only
Tests full controller request pipelines
Tests security headers in production
Tests database access with live server
In controller testing, what is a common practice to handle external services?
Mock dependencies for isolation
Use real services in staging
Bypass services with manual calls
Disable services during tests
Repository testing primarily verifies which concern?
View rendering with Razor pages
Client-side JavaScript execution
Authorization policies for roles
Data access behavior and queries
Security testing in an MVC app typically includes which check?
CPU usage under load tests
Size of compiled assemblies
Number of integration endpoints
Presence of security headers
Match the test structure steps to their purpose using GOAL, LOGIC, RESULT.
RESULT defines expected outcome
LOGIC defines how to test
GOAL defines what to test
None of these are correct
Which test type validates the system end-to-end across components?
Controller tests for actions
Security tests for headers
Unit tests for single methods
Integration tests across the system
You need to verify a controller returns a redirect when a repository reports no data. Which testing approach fits best?
Security test for CSP headers
Integration test without mocks
Unit test with live database
Controller test with mocked repository
A team chooses an InMemory database to validate repository methods. What is the primary benefit in this context?
Automatic security policy setup
Fast, isolated data operations
Accurate production traffic
Enhanced client-side caching
Which statement best describes Docker in modern application deployment?
Virtual machine hypervisor for full OS images
Container technology packaging apps and dependencies
Cloud orchestration platform for autoscaling clusters
Source control system for microservices revisions
In a typical docker-compose.yml for an ASP.NET Core app with MariaDB, which two services are defined?
aspnet app and mariadb
frontend and redis
api gateway and kafka
webapp and mongodb
What is the primary benefit of containerization for deployment?
Maximizes hardware virtualization overhead
Ensures consistent runtime across environments
Eliminates need for application configuration
Requires dedicated physical servers for apps
Which port mapping is commonly shown for the web application in the provided scenario?
8080:8080 for app service
80:8080 for app service
443:5000 for app service
3307:3306 for app service
What happens first when running docker-compose for this stack?
Docker starts the MariaDB container
Docker builds the ASP.NET application
Application migrations execute immediately
The app connects to the database
Which step indicates the application becoming operational with its database?
Images are pushed to a registry
Ports are closed to external traffic
Docker daemon restarts the host
The app connects to the database
After all steps complete, how are the components running?
As local processes without isolation
In containers managed by Docker
On serverless functions only
In separate VMs with full OS
Which statement best describes MariaDB in the context of web application development?
Non-relational store for documents
Relational database storing data in tables
Message queue for background jobs
In-memory cache for session data
Why might a team choose MariaDB for an ASP.NET Core MVC project?
Optimized only for NoSQL workloads
Closed source with paid support
Limited compatibility with EF Core
Open source, reliable, works well with EF
Which comparison between MySQL and MariaDB is most accurate for typical usage?
MySQL is only for Windows servers
They are entirely different engines
They are nearly identical for most tasks
MariaDB cannot run SQL joins
Given the connection string 'Server=mariadb;Database=Kartverketdb;User=root;Password=root123', which change correctly targets a different database name while keeping other settings the same?
Server=sql;Database=Kartverketdb;User=admin;Password=pass
Server=mariadb;Database=ReportsDb;User=root;Password=root123
Server=localhost;Database=ReportsDb;User=sa;Password=pass
Server=mysql;Database=Kartverketdb;User=root;Password=root123
In a relational database schema for an MVC app, which relationship example aligns with typical foreign-key usage?
Middleware to Database as one-to-many
Controller to View as one-to-one
User to Organization as many-to-many
Report to Obstacles as one-to-many
When querying related data using Entity Framework Core, which method helps eagerly load relationships like Obstacles with their Report?
AddRange
ExecuteScalar
Include
SaveChanges
In a relational database, what role does a foreign key primarily serve?
Optimize query execution plans
Store large binary objects
Link rows between related tables
Identify unique rows in a table
Which scenario best exemplifies a one-to-many relationship in an EF Core domain?
Many Users have many Roles
One Report has many Obstacles
One User belongs to many Organizations
Many Organizations belong to one User
To eagerly fetch related data for Obstacles and their Report in EF Core, which method call should be used?
_context.Obstacles.Select(o => o.Report)
_context.Obstacles.Include(o => o.Report)
_context.Obstacles.Load(o => o.Report)
_context.Obstacles.Attach(o => o.Report)
Which statement correctly describes a many-to-one relationship?
One entity references itself in many rows
One child references many parents
Many child entities reference one parent
Many parent entities reference one child
In EF Core, what is the typical effect of using Include on a query?
Deletes orphaned related entities
Performs lazy loading of related entities
Adds a join to load related entities
Creates new related entities automatically
Which file type is used to create Razor Views in an ASP.NET Core MVC application?
.cshtml files for views
.razor files for views
.html files for views
.aspx files for views
In the frontend stack described, what is the primary purpose of Bootstrap?
Database connectivity
Server-side rendering
Styling and UI components
Client-side routing support
Which statement best describes Razor Views in ASP.NET Core MVC?
JavaScript-only templates
HTML mixed with C# code
CSS-only components
XML-based view files
A project includes map.js and draft.js. What is the most likely responsibility of these files?
Unit testing, integration tests
Authentication, authorization
Map for geolocation, form handling
Data seeding, migrations
You need the UI to adapt well on iPad and PC. Which concept should you apply?
Shadow DOM encapsulation
Progressive enhancement approach
Server-side caching rules
Responsive design techniques
In Razor Views, which directive is commonly used to pass data from the controller to the view?
@page directive for data
@using directive for data
@Model directive for data
@inject directive for data
In ASP.NET Core using EF Core, what is the primary purpose of a database migration?
Modify data seeding values across environments
Update database structure to match models
Optimize query performance for specific endpoints
Enable real-time syncing between contexts and views
Which statement best describes how EF Core handles SQL during migrations?
It uses stored procedures created by controllers
It compiles Razor views into SQL commands
It generates SQL from model definitions
It requires hand-written SQL for every change
You added a new property to an entity. Which action correctly applies the corresponding schema change to the database?
Run dotnet ef database update after creating a migration
Call the controller constructor with a repository instance
Restart the web app without adding a migration
Manually edit tables using the SQL Server GUI
A team wants migrations to apply without manual commands during deployment. Which approach aligns with this goal?
Use AJAX requests to call the obstacles controller
Trigger updates by posting a form with validation
Execute update statements from a Razor view during rendering
Configure migrations to run automatically at application startup
In a controller using the Repository pattern, what is the primary benefit of injecting an interface like IObstacleRepository into the constructor?
Guarantees database transactions succeed
Allows automatic Razor view compilation
Enables loose coupling and testability
Improves runtime reflection performance
A POST action is decorated with [ValidateAntiForgeryToken]. What specific risk does this attribute mitigate?
SQL injection in queries
Cross-Site Scripting payloads
Cross-Site Request Forgery attacks
Man-in-the-middle interception
In an ASP.NET Core MVC controller, which condition should typically short-circuit a POST action to redisplay the view with user input?
ViewData count is zero
HttpContext.Request.IsHttps
User.Identity.IsAuthenticated
ModelState.IsValid is false
Given an EF Core repository method that returns await _context.Obstacles.Include(o => o.Report).FirstOrDefaultAsync(o => o.Id == id); what does Include(o => o.Report) achieve?
Filters rows by Report fields
Eager loads related Report entity
Defers loading until first access
Creates a database transaction scope
Which statement best describes FirstOrDefaultAsync with a predicate like o => o.Id == id in EF Core?
Blocks the thread until completion
Returns all matching entities in a list
Always throws if no entity exists
Returns the first matching entity or null
You must design a Login POST action. Which minimal set of attributes and checks aligns with secure and validated submission in ASP.NET Core MVC?
[HttpPost] only, rely on client-side checks
[AcceptVerbs("POST","PUT")], skip validation
[HttpGet] and [Authorize], ignore ModelState
[HttpPost] and [ValidateAntiForgeryToken], check ModelState
When using a repository in a controller, which code pattern correctly applies Dependency Injection for the repository field?
Repository created with ActivatorUtilities each call
Public settable field, modified in Startup
Static repository instance, newed inside action
Private readonly interface field, assigned via constructor
