Autocoder

ASP.NET Core MVC Interview Questions

Last updated 2026-11-19

ASP.NET Core MVC interviews concentrate on the request flow: how a URL becomes an action, how request data is bound to parameters, which filters run in what order, and how views get their data. Security topics such as anti-forgery tokens, authorisation policies and over-posting are standard follow-ups.

This page focuses on the MVC and Web API layer. Platform topics such as the middleware pipeline, dependency injection lifetimes and hosting are on the .NET Core page, and data access is on Entity Framework Core.

FrameworkASP.NET Core MVC on .NET 8
PatternModel, View, Controller with endpoint routing
Also coveredWeb API controllers and filters

Request flow in one pass

A request passes the middleware pipeline, endpoint routing selects a controller action, authorisation and resource filters run, model binding and validation populate the parameters, action filters wrap the action, the action returns an IActionResult, result filters run, and the result executes (rendering a Razor view or writing JSON). Exception filters wrap the action and its filters.

ASP.NET Core MVC Interview Questions: questions with worked answers

  1. 1

    Explain MVC and how ASP.NET Core implements it.

    easy

    The Model holds data and rules, the View renders output (Razor templates), and the Controller handles the request, calls the model and picks a view or returns data. Separating them lets each be tested and changed independently. In ASP.NET Core a controller is a class with public action methods, discovered by endpoint routing, and views live under Views/{Controller}/{Action}.cshtml by convention.

  2. 2

    Conventional versus attribute routing.

    medium

    Conventional routing defines URL patterns centrally, such as {controller=Home}/{action=Index}/{id?}, and suits page-style sites. Attribute routing puts [Route], [HttpGet("{id}")] and similar attributes on controllers and actions and is the norm for APIs because the URL is next to the code. They can be mixed in a project, but an action with an attribute route is not reachable by conventional routes.

    csharp
    app.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
    
    [ApiController]
    [Route("api/[controller]")]
    public class OrdersController : ControllerBase {
        [HttpGet("{id:int}")]
        public ActionResult<Order> Get(int id) => ...;
    }
  3. 3

    Controller versus ControllerBase, and what does [ApiController] add?

    medium

    ControllerBase has the core API features such as Ok, NotFound and ModelState, and Controller adds view support (View, PartialView, TempData). [ApiController] adds conventions: automatic HTTP 400 with ProblemDetails when ModelState is invalid, binding source inference ([FromBody] for complex types, [FromRoute] and [FromQuery] for simple ones), a requirement for attribute routing and problem-details responses for error status codes.

  4. 4

    IActionResult versus ActionResult<T>.

    medium

    IActionResult can return any result but hides the success type from OpenAPI generators. ActionResult<T> lets you return either T directly or an ActionResult such as NotFound, so Swagger documents the response type without extra attributes. Use async Task<ActionResult<T>> for I/O.

    csharp
    [HttpGet("{id}")]
    public async Task<ActionResult<Product>> Get(int id) {
        var p = await _repo.FindAsync(id);
        if (p is null) return NotFound();
        return p;            // implicit conversion to 200 OK with JSON
    }
  5. 5

    How does model binding work? Name the binding sources.

    medium

    Model binding reads values from the request and maps them to action parameters and model properties by name. The default sources, in order, are form values, route data and the query string; attributes override this: [FromBody] reads JSON from the body (only one allowed per action), [FromQuery], [FromRoute], [FromHeader], [FromForm] and [FromServices] for dependency injection. Failures set ModelState errors rather than throwing.

    csharp
    [HttpPost("{id}")]
    public IActionResult Update(
        [FromRoute] int id,
        [FromQuery] bool notify,
        [FromHeader(Name = "X-Trace")] string? trace,
        [FromBody] UpdateDto body) => Ok();
  6. 6

    How does validation work, and what is ModelState?

    medium

    Data annotations such as [Required], [StringLength], [Range] and [EmailAddress] on a model are checked after binding, and the results go into ModelState. In MVC you test ModelState.IsValid and redisplay the form; with [ApiController] an invalid model automatically returns 400. Complex rules use IValidatableObject, custom attributes or libraries such as FluentValidation. Client-side validation in views is generated from the same annotations by the unobtrusive validation scripts, but server validation is mandatory.

    csharp
    public class RegisterDto {
        [Required, EmailAddress] public string Email { get; set; } = "";
        [Range(18, 120)] public int Age { get; set; }
    }
    [HttpPost]
    public IActionResult Register(RegisterDto dto) {
        if (!ModelState.IsValid) return View(dto);
        return RedirectToAction("Done");
    }
  7. 7

    Explain filters and the order in which they run.

    medium

    Filters hook into the MVC pipeline. The order is authorisation filters, resource filters, then model binding, action filters (before and after the action), and result filters (before and after the result executes); exception filters handle exceptions from actions and action filters. Filters run in the order of scope: global, then controller, then action, with the order reversed on the way out. They can be registered globally, as attributes or with TypeFilter and ServiceFilter to get dependency injection.

    csharp
    public class TimingFilter : IAsyncActionFilter {
        public async Task OnActionExecutionAsync(ActionExecutingContext ctx, ActionExecutionDelegate next) {
            var sw = Stopwatch.StartNew();
            await next();
            Console.WriteLine($"{ctx.ActionDescriptor.DisplayName}: {sw.ElapsedMilliseconds} ms");
        }
    }
    builder.Services.AddControllers(o => o.Filters.Add<TimingFilter>());
  8. 8

    Filters versus middleware: when do you use each?

    medium

    Middleware runs for every request, before routing decides what to execute, and sees only the HttpContext, so it suits cross-cutting concerns such as logging, CORS, authentication and compression. Filters run only for requests that reach MVC and have access to the action, parameters, model state and results, so they suit concerns such as action-specific validation, caching headers and wrapping action results.

  9. 9

    ViewData, ViewBag and TempData: what is the difference?

    easy

    ViewData is a dictionary passed from controller to view for one request and ViewBag is a dynamic wrapper over the same data. A strongly typed view model is preferable to both. TempData survives until it is read in a later request, storing values in a cookie or session, which makes it ideal for flash messages after a redirect, and Peek and Keep let you retain a value.

    csharp
    public IActionResult Save(Model m) {
        // ...
        TempData["Message"] = "Saved";
        return RedirectToAction(nameof(Index));   // Post/Redirect/Get
    }
  10. 10

    What are partial views, view components and tag helpers?

    medium

    A partial view is a reusable fragment rendered with the partial tag helper and shares the parent model or gets its own. A view component is like a mini controller with its own logic and can load data independently, for a cart summary or menu. Tag helpers add server-side behaviour to HTML-like tags such as asp-action and asp-for, producing correct URLs and field names, and replaced most HtmlHelper calls.

  11. 11

    How does authentication differ from authorisation, and what is policy-based authorisation?

    hard

    Authentication establishes who the user is (cookie, JWT bearer, OpenID Connect); authorisation decides what they may do. [Authorize] requires an authenticated user, and Roles restricts by role claim. A policy bundles requirements, such as a minimum age claim or a custom handler that inspects the resource, and is applied with [Authorize(Policy = "...")]; this is more flexible than role strings. UseAuthentication must come before UseAuthorization in the pipeline.

    csharp
    builder.Services.AddAuthorization(o =>
        o.AddPolicy("Adult", p => p.RequireClaim("age").RequireAssertion(
            ctx => int.Parse(ctx.User.FindFirst("age")!.Value) >= 18)));
    [Authorize(Policy = "Adult")]
    public IActionResult Adults() => View();
  12. 12

    What is CSRF, and how does ASP.NET Core protect against it?

    medium

    Cross-site request forgery tricks a logged-in browser into submitting a state-changing request, because cookies are sent automatically. The form tag helper emits an anti-forgery token, and [ValidateAntiForgeryToken] or the AutoValidateAntiforgeryToken global filter verifies it on POST. APIs that authenticate with a bearer token in a header rather than a cookie are not vulnerable to CSRF in the same way.

  13. 13

    What is over-posting and how do you prevent it?

    medium

    Over-posting means a client sends extra fields that the binder maps onto model properties you did not intend, such as IsAdmin. Prevent it by binding to a dedicated view model or DTO that contains only the fields the form allows, and map to the entity yourself, or restrict with [Bind] or [BindNever], though DTOs are cleaner.

  14. 14

    How should errors be handled in MVC and APIs?

    medium

    Use UseExceptionHandler for unhandled exceptions with an error page or a ProblemDetails response, and UseStatusCodePages or UseStatusCodePagesWithReExecute for 404 and similar. In APIs return ProblemDetails (RFC 7807, enabled by AddProblemDetails) for a consistent JSON shape, and keep stack traces out of production responses. Exception filters or an IExceptionHandler (.NET 8) can map domain exceptions to status codes.

    csharp
    builder.Services.AddProblemDetails();
    app.UseExceptionHandler();
    app.UseStatusCodePages();
  15. 15

    What are the caching options?

    medium

    Response caching headers (ResponseCache attribute) let clients and proxies cache. Output caching (.NET 7 and later) caches responses on the server with policies and tag-based invalidation. IMemoryCache stores objects in process, and IDistributedCache with Redis shares them across servers. Cache only what is safe to share, and vary by the inputs that change the response.

  16. 16

    Razor Pages versus MVC: how do they differ?

    medium

    Razor Pages organise each page as a .cshtml file with a PageModel handling its requests, so the view and its logic are together, which suits page-focused apps. MVC separates controllers, views and models and gives more flexibility for large applications with shared actions. Both use the same underlying framework, filters, model binding and Razor syntax, and can live in one application.

  17. 17

    How do API versioning and CORS fit into API controllers?

    medium

    Versioning (the Asp.Versioning packages) lets you keep old routes working through URL segments, query strings or headers. CORS is a browser rule: the server must send Access-Control-Allow-Origin headers for cross-origin calls, configured with AddCors and UseCors, naming specific origins rather than allowing all in production. CORS does not protect the server, only tells browsers what scripts may read.

Frequently asked questions

Is MVC still used in .NET 8?

Yes. MVC, Razor Pages and minimal APIs coexist; many enterprise apps use MVC or controller-based APIs.

What is the difference between Web API and MVC?

Both use controllers on one framework. Web API returns data (JSON) and MVC also returns views; ControllerBase is the API base class.

What should a fresher know first?

Request flow, routing, model binding, validation and the difference between ViewData and TempData.

What comes after MVC in a .NET learning path?

Data access with Entity Framework Core and the platform concepts on .NET Core.

Related guides

More in Programming Language Interview Questions by Language

See all in this section