**JasperReports** and 25 on **ASP.NET MVC**

Below are **50 succinct question-and-answer pairs**—25 on **JasperReports** and 25 on **ASP.NET MVC**—that hiring managers commonly use to probe both conceptual understanding and hands-on skill.


---


### JasperReports (1 – 25)


1. **Q:** *What is JasperReports and where is it typically used?*

   **A:** JasperReports is an open-source Java reporting engine that lets developers design, compile, and render highly formatted documents (PDF, XLSX, DOCX, HTML, etc.). It’s embedded inside Java applications, micro-services, or exposed via JasperReports Server for self-service BI dashboards.


2. **Q:** *What is a JRXML file?*

   **A:** It’s an XML design file containing bands, fields, parameters, queries, and styles. At runtime it is compiled into a binary *.jasper* file that the engine can fill quickly.


3. **Q:** *Why must a JRXML be compiled?*

   **A:** Compilation converts the declarative XML into optimized Java bytecode (a `JasperReport` object). This speeds up filling and enables runtime expression evaluation.


4. **Q:** *Name three built-in data sources JasperReports supports.*

   **A:** JDBC connections, JavaBean collections, and CSV/JSON/XML flat files.


5. **Q:** *How do you pass a date range parameter to a report?*

   **A:** Define `$P{StartDate}` and `$P{EndDate}` in the JRXML, reference them in the SQL (`WHERE order_date BETWEEN $P!{StartDate} AND $P!{EndDate}`), then supply `java.util.Date` values in the fill call:


   ```java

   params.put("StartDate", start); params.put("EndDate", end);

   ```


6. **Q:** *Difference between “Detail” and “Summary” bands?*

   **A:** The Detail band repeats for every record; Summary prints once at the end, ideal for totals.


7. **Q:** *When would you use a sub-report?*

   **A:** For master-detail layouts (e.g., invoice header → line items) or to reuse a complex component across many parent reports.


8. **Q:** *Explain lazy loading of sub-reports.*

   **A:** With `net.sf.jasperreports.subreport.runner.factory` you can delay sub-report execution until it’s scrolled to in an interactive viewer, reducing initial memory footprint for huge reports.


9. **Q:** *How do you localize static text?*

   **A:** Reference keys (`$R{title}`) and provide language-specific `ResourceBundle` *.properties* files.


10. **Q:** *What is a scriptlet?*

    **A:** A custom Java class extending `JRDefaultScriptlet`; it hooks into `beforeReportInit`, `afterGroupInit`, etc., allowing advanced logic that expressions alone can’t handle.


11. **Q:** *How do you embed an image stored as a BLOB?*

    **A:** Map the column as a `java.io.InputStream` field and set the image’s “Expression Class” to `java.io.InputStream`.


12. **Q:** *Steps to export to PDF programmatically.*

    **A:** Fill → obtain `JasperPrint` → call `JasperExportManager.exportReportToPdfStream(jp, outputStream)`.


13. **Q:** *Best practice to avoid “blank pages” between groups?*

    **A:** Disable “Print When Detail Overflows” on unused bands and ensure band heights plus top/bottom margins fit within the page height.


14. **Q:** *How do you add a custom font?*

    **A:** Create a font extension JAR with `font-family.xml`, register in classpath, and reference the font in styles; embed it for PDF by ticking “PDF Embedded”.


15. **Q:** *What causes “JRVirtualizer memory overflow” and how to fix it?*

    **A:** Giant reports store pages in RAM. Enable `JRFileVirtualizer` or `JRSwapFileVirtualizer` so overflowing pages spill to temp files.


16. **Q:** *Difference between JasperReports Library and JasperReports Server?*

    **A:** Library is the core engine for embedding; Server adds repository, user/role security, scheduling, REST APIs, and interactive dashboards.


17. **Q:** *How do you schedule a report e-mail in JasperReports Server?*

    **A:** From the UI → “Schedule” → pick cron, output type, mail settings. Internally it creates a Quartz job.


18. **Q:** *How are table components implemented?*

    **A:** They’re sub-datasets rendered via special matrix elements; each column is itself a JR design cell, letting you nest other components.


19. **Q:** *Can you call a stored procedure?*

    **A:** Yes—set the query language to “plsql” or prepend `{call my_proc(?,?)}` in the main dataset and supply parameters.


20. **Q:** *How to mask sensitive data like credit-card numbers?*

    **A:** Use a text-field expression such as


    ```java

    $F{cc}.replaceAll(".(?=.{4})", "*")

    ```


21. **Q:** *Purpose of `Print Order = Horizontal`?*

    **A:** Fills detail rows across columns first (labels, coupons) before moving downward.


22. **Q:** *Explain report pagination in XLSX export.*

    **A:** XLSX ignores physical pages; set exporter hint `IS_ONE_PAGE_PER_SHEET` to keep each report page on its own worksheet if desired.


23. **Q:** *Troubleshooting missing data but SQL works in DB client?*

    **A:** Ensure parameter types match database types; or check if JRXML query was overwritten by a dataset *run-time* query.


24. **Q:** *Why choose JavaBean data source over JDBC?*

    **A:** When data is already aggregated in memory, when joining multiple micro-service calls, or to avoid tight DB coupling.


25. **Q:** *What library do charts rely on?*

    **A:** JFreeChart underpins pie, bar, line, etc., components.


---


### ASP.NET MVC (26 – 50)


26. **Q:** *What problem does ASP.NET MVC solve compared with Web Forms?*

    **A:** It enforces separation of concerns (UI, logic, data), gives full control over markup, supports test-driven development, and avoids ViewState overhead.


27. **Q:** *Describe the request lifecycle.*

    **A:** Route matching → `MvcHandler` → Controller instantiation via DI → Action execution → Result (usually a View) → View Engine renders Razor → Response.


28. **Q:** *What is routing?*

    **A:** A URL-pattern mapping mechanism. Conventional routing uses templates like `{controller}/{action}/{id}`; attribute routing decorates actions with `[Route("api/orders/{id:int}")]`.


29. **Q:** *How does model binding work?*

    **A:** It reads form fields, query-string, route data, or JSON body and populates action parameters or view-model properties using value providers and type converters.


30. **Q:** *Difference between ViewBag, ViewData, and TempData?*

    **A:** ViewBag (dynamic) and ViewData (dictionary) live for one request; TempData persists until read (session-backed), useful after redirects.


31. **Q:** *How do you enable unobtrusive client-side validation?*

    **A:** Add `jquery.validate` and `jquery.validate.unobtrusive` scripts; decorate view-model with Data Annotations (`[Required]`), and include `@Html.ValidationSummary()` in the view.


32. **Q:** *Explain Razor syntax benefits.*

    **A:** Clean `@` code nuggets, no separate designer; compiles to C# classes, enabling IntelliSense and compile-time errors.


33. **Q:** *What are partial views?*

    **A:** Reusable view fragments rendered inside other views via `@Html.Partial` or asynchronously with `@await Html.PartialAsync`.


34. **Q:** *How do you implement dependency injection?*

    **A:** In MVC 5 use a DI container like Autofac and set a custom `IDependencyResolver`; in ASP.NET Core, services are registered in `ConfigureServices`.


35. **Q:** *How can you protect against CSRF?*

    **A:** Include `@Html.AntiForgeryToken()` in forms and annotate actions with `[ValidateAntiForgeryToken]`.


36. **Q:** *Difference between `HttpPost` and `HttpPut` attributes?*

    **A:** Both restrict verbs; POST typically creates resources, PUT replaces/updates. In MVC these attributes ensure routing matches the correct action.


37. **Q:** *Why use asynchronous controllers?*

    **A:** To free up threads during I/O (DB, HTTP) and improve scalability. Implement with `async Task<ActionResult>` and `await`.


38. **Q:** *What is bundling and minification?*

    **A:** Framework feature that combines and compresses CSS/JS. In MVC 5 via `BundleConfig`; in Core via `gulp`/`webpack` or built-in `TagHelper` libraries.


39. **Q:** *How do you return JSON data?*

    **A:** Use `return Json(obj, JsonRequestBehavior.AllowGet)` in MVC 5 or `return Json(obj);` in Core (automatic).


40. **Q:** *Purpose of `ActionFilterAttribute`?*

    **A:** To intercept pre/post action logic (logging, caching, auth). Override `OnActionExecuting/Executed`.


41. **Q:** *Explain view component vs. partial view in ASP.NET Core.*

    **A:** View component has its own class, accepts parameters, supports async logic; partial view is static markup rendering.


42. **Q:** *How do you handle global errors?*

    **A:** Configure `customErrors` in `web.config` or use `HandleErrorAttribute` (MVC 5). In Core, set up `UseExceptionHandler("/Error")` middleware.


43. **Q:** *Describe server-side caching strategies.*

    **A:** OutputCache (MVC 5) or ResponseCache attribute (Core) for whole pages; MemoryCache/DistributedCache for data; vary by headers, params, or roles.


44. **Q:** *Unit testing a controller action?*

    **A:** Instantiate controller with mocked services, call action, assert result type and model values using xUnit/NUnit and Moq/FakeItEasy.


45. **Q:** *What are tag helpers?*

    **A:** In Core, C# classes that produce HTML elements, e.g., `<form asp-action="Login">`; they provide IntelliSense and server-side processing similar to HTML helpers.


46. **Q:** *How would you stream a Jasper PDF via an MVC controller?*

    **A:**


    ```csharp

    var bytes = JasperExportManager.exportReportToPdf(jasperPrint);

    return File(bytes, "application/pdf", "report.pdf");

    ```


47. **Q:** *Approach for SSO between MVC portal and JasperReports Server?*

    **A:** Use SAML or OAuth2; configure JasperReports’ external authentication with a custom `ExternalUserProcessor`, and MVC acts as the identity provider.


48. **Q:** *How to upload a file securely?*

    **A:** Validate mime type, file size limits, store outside wwwroot, scan for malware, and use `IFormFile` or `HttpPostedFileBase`.


49. **Q:** *What’s the role of middleware in ASP.NET Core compared to HttpModules?*

    **A:** Middleware forms a configurable request pipeline (delegates). It replaces the earlier module/handler system with more granular, ordered components.


50. **Q:** *How can you monitor slow MVC requests and Jasper report generation?*

    **A:** Add Application Insights or ELK stack logging for MVC; enable JasperReports’ built-in log4j statistics and hook both into centralized APM dashboards.


---


These Q\&A pairs cover core concepts, common pitfalls, and integration touch-points that interviewers expect candidates to know when working with JasperReports and ASP.NET MVC.



Below is a quick historical rundown of every *major* ASP.NET-MVC generation, split into the two eras Microsoft now distinguishes:

---

## 1. “Classic” ASP.NET MVC (on the .NET Framework)

| Version                              | First GA date | Target .NET Framework | Headline additions                                                                                |
| ------------------------------------ | ------------- | --------------------- | ------------------------------------------------------------------------------------------------- |
| MVC 1.0                              | 13 Mar 2009   | 3.5 SP1               | Core MVC pattern on top of Web Forms pipeline, HTML Helpers, routing ([en.wikipedia.org][1])      |
| MVC 2                                | 10 Mar 2010   | 3.5 SP1/4.0           | Areas, strongly-typed HTML helpers, client-side validation ([en.wikipedia.org][1])                |
| MVC 3                                | 13 Jan 2011   | 4.0                   | Razor view engine, global filters, partial page output caching ([en.wikipedia.org][1])            |
| MVC 4                                | 15 Aug 2012   | 4.0/4.5               | Web API 1 integration, mobile templates, Bundling & Minification ([en.wikipedia.org][1])          |
| MVC 5 (latest patch 5.3.0, Oct 2023) | 17 Oct 2013   | 4.5.1                 | Attribute routing, filter overrides, bootstrap-based templates, OWIN auth ([en.wikipedia.org][1]) |

> **Note** “MVC 6” was folded into the new **ASP.NET Core** stack; it never shipped as a separate classic release.

---

## 2. ASP.NET Core MVC (cross-platform, versioned with .NET)

| ASP.NET Core MVC release            | Underlying .NET / release type | Key new-features snapshot                                             | Support window\*                                 |
| ----------------------------------- | ------------------------------ | --------------------------------------------------------------------- | ------------------------------------------------ |
| 1.0 (“MVC 6”) – Jun 2016            | .NET Core 1.0 (RTM)            | Built-in DI, Tag Helpers, cross-platform Kestrel host                 | Ended Jun 2019 ([learn.microsoft.com][2])        |
| 1.1 – Nov 2016                      | .NET Core 1.1                  | View-components caching, URL rewriting                                | Ended Jun 2019 ([learn.microsoft.com][2])        |
| 2.0 – Aug 2017                      | .NET Core 2.0                  | Razor Pages, simplified program/host startup                          | Ended Oct 2018 ([learn.microsoft.com][2])        |
| 2.1 (LTS) – May 2018                | .NET Core 2.1                  | `IHttpClientFactory`, GDPR templates, HTTPS by default                | Ended Aug 2021 ([learn.microsoft.com][2])        |
| 2.2 – Dec 2018                      | .NET Core 2.2                  | Endpoint routing (preview), health-checks                             | Ended Dec 2019 ([learn.microsoft.com][2])        |
| 3.0 – Sep 2019                      | .NET Core 3.0                  | gRPC, Blazor Server, Worker Service template                          | Ended Mar 2020 ([learn.microsoft.com][2])        |
| 3.1 (LTS) – Dec 2019                | .NET Core 3.1                  | Long-term support release, System.Text.Json default                   | Ended Dec 2022 ([learn.microsoft.com][2])        |
| 5.0 – Nov 2020                      | .NET 5 (STS)                   | Single-file publish, improved gRPC & SignalR perf                     | Ended May 2022 ([learn.microsoft.com][2])        |
| 6.0 (LTS) – Nov 2021                | .NET 6                         | Minimal APIs, Hot-Reload, async streaming                             | Ends Nov 2024 ([learn.microsoft.com][2])         |
| 7.0 – Nov 2022                      | .NET 7 (STS)                   | Rate-limiting middleware, Minimal-API filters                         | Ended May 2024 ([learn.microsoft.com][2])        |
| 8.0 (LTS) – Nov 2023                | .NET 8                         | Native AOT for web, Blazor Full-Stack, output-caching middleware      | Active till Nov 2026 ([dotnet.microsoft.com][3]) |
| 9.0 – Nov 2024                      | .NET 9 (STS)                   | ASP.NET Core “server components”, improved SIMD JSON, HTTP/3 promoted | Active till May 2026 ([dotnet.microsoft.com][3]) |
| 10.0 preview (coming Nov 2025, LTS) | .NET 10                        | Early previews focus on cloud-optimised WASM, data-shaping APIs       | —                                                |

\*Support windows follow Microsoft’s **Modern Lifecycle**: LTS = 3 years; STS = 18 months.

---

### How to choose for new projects (2025)

* **Green-field**: start on **ASP.NET Core 8 LTS** unless you need features that landed in 9.0 STS and you can tolerate its shorter support.
* **Maintaining classic MVC**: MVC 5.3.0 on .NET Framework is still patched for security, but no new features—plan a migration path to Core for long-term viability.
* **Migration tip**: move first to .NET 6/8 with the **MVC compatibility-shim** (`Microsoft.AspNetCore.Mvc.Api.Analyzers` + `Microsoft.AspNetCore.Mvc.ViewFeatures`), then refactor toward Minimal APIs or Razor Pages as needed.

These version milestones should help you map project requirements to the right ASP.NET-MVC generation and support horizon.

[1]: https://en.wikipedia.org/wiki/ASP.NET_MVC "ASP.NET MVC - Wikipedia"
[2]: https://learn.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core "Microsoft .NET and .NET Core - Microsoft Lifecycle | Microsoft Learn"
[3]: https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core ".NET and .NET Core official support policy | .NET"

以下教學以 **「把 Asp .NET MVC 作為前端/中介層」**,呼叫 **JasperReports** 來產生 PDF 或其他格式報表為目標。
由於 JasperReports 仍是 **Java 生態系** 的產品,在 .NET 世界最常見的做法是「**服務化**」──把報表放在 **JasperReports Server**(或輕量的 **JasperReports IO**)後,以 REST API 方式呼叫,再把二進位串流回傳給使用者瀏覽器。以下分三種常用模式說明:

---

## 方案 A ─ 直接呼叫 JasperReports Server REST v2(最常見)

### 1 . 在 JasperReports Server 上準備報表

1. 於 **Jaspersoft Studio** 設計 `MyInvoice.jrxml`。
2. 登入 JasperReports Server(本文以 v9 LTS 為例)➜ 右鍵 *Repository* ➜ *Add Resource ▷ Report Unit* ➜ 上傳 `jrxml`,設定資料來源與所需參數。

   > Server 9.x 提供 REST v2 `/rest_v2` 端點,文件詳見官方「The reports Service」章節 ([community.jaspersoft.com][1])

### 2 . 在 ASP.NET MVC 建立 Controller

```csharp
// using System.Net.Http;
// using System.Net.Http.Headers;
// using Microsoft.AspNetCore.Mvc;
// 假設 .NET 8 / ASP.NET Core MVC,舊版 MVC 5 僅 ActionResult 與 DI 寫法略有差異

[Route("reports")]
public class ReportController : Controller
{
    private readonly IHttpClientFactory _httpFactory;
    private const string JasperBase = "http://jasperhost:8080/jasperserver";

    public ReportController(IHttpClientFactory factory) => _httpFactory = factory;

    [HttpGet("invoice/{id}")]
    public async Task<IActionResult> Invoice(int id)
    {
        // 1) 取得 HttpClient 並放 Basic Auth (可改成 token-based 或 SSO cookie)
        var client = _httpFactory.CreateClient();
        var credential = Convert.ToBase64String(
            Encoding.ASCII.GetBytes("jasperadmin:Password1"));
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Basic", credential);

        // 2) REST v2 直接產出 PDF;參數用 query-string
        var uri =
            $"{JasperBase}/rest_v2/reports/Reports/Finance/Invoice.pdf?InvoiceId={id}";
        var pdfBytes = await client.GetByteArrayAsync(uri);

        // 3) 直接串流回瀏覽器
        return File(pdfBytes, "application/pdf", $"invoice-{id}.pdf");
    }
}
```

* **說明**

  * 只要 `GET …/reportPath.pdf?...` 就會拿到二進位 PDF。將 `.pdf` 改成 `.xlsx`、`.docx`、`.html` 等即可輸出其他格式。
  * 若報表需要大量參數或要 POST JSON,可改用 `/rest_v2/reports/{path}` **POST**,body = `application/x-www-form-urlencoded` 或 `application/xml`。
  * 若公司要整合 SSO,可先 `POST /rest_v2/login` 建立 Session,再帶 Cookie 呼叫報表。

---

## 方案 B ─ JasperReports IO (JR IO) Micro-Service

* JasperReports IO 4.0 與 Server 共用相同引擎,但定位成「無 UI、純 REST」。啟動(Docker 或 Jar)後有端點 `/report`。
* 範例 POST:

  ```http
  POST /jrio/rest_v1/report
  Content-Type: application/json

  {
    "reportUnit": "/reports/Finance/Invoice",
    "outputFormat": "pdf",
    "params": { "InvoiceId": 123 }
  }
  ```
* 在 MVC 只需把上面 POST 透過 HttpClient 送出,再把回傳的 `Content‐Disposition: attachment;filename=…` 取出並串流回瀏覽器即可。
* JR IO 檔案系統可掛 Git volume,或透過其管理 API 熱更新 jrxml ([community.jaspersoft.com][2])。

---

## 方案 C ─ JasperStarter / 自建 Java 微服務

若 **無法部署 JasperReports Server**(授權或資源限制),可在後端併行一支輕量 **Spring Boot + JasperReports Library** 的服務(或乾脆用 **JasperStarter CLI**):

1. Java 端提供 `POST /generate`:接收 JSON → 用 `JasperFillManager.fillReport` → `JasperExportManager.exportReportToPdf` → 回傳 bytes。
2. .NET MVC 與方案 A 類似,以 HttpClient 呼叫即可。

---

## MVC View 端直接嵌入(可選)

若要在 Razor View 直接顯示互動版報表,可引入 **Visualize.js**:

```html
<script src="http://jasperhost:8080/jasperserver-pro/client/visualize.js"></script>
<div id="report"></div>
<script>
  visualize({
    auth: { name: "jasperadmin", password: "Password1" }
  }, function (v) {
      v("#report").report({
          resource: "/reports/Finance/Invoice",
          params: { InvoiceId: 123 }
      });
  });
</script>
```

前端不用重新整理頁面就能切換參數。

---

## 常見問題與最佳實務

| 問題               | 重點建議                                                                                                                                  |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **大量報表導致記憶體爆裂**  | 開啟 **虚擬化 (JRFileVirtualizer)** 或在 Server 側設 `jr.page.break.policy=on`。                                                                |
| **需要分時段佇列產生**    | 用 JasperReports Server 內建 **Scheduler (Quartz)**,或由 MVC 建立 background job(Hangfire/Azure Functions)打 REST。                            |
| **需要動態上傳 jrxml** | Server REST `PUT /resources`,或 JR IO 管理端點—交由 CI/CD 管 jrxml 版本。                                                                        |
| **安全性**          | Production 務必關閉 HTTP Basic,改用 LDAP/SAML/OAuth;ASP.NET Core 可用 OpenID Connect middleware 與 Server 的 OAuth 功能相對接 ([jaspersoft.com][3])。 |
| **中文/特殊字無法顯示**   | 在 JasperReports Server 裝 **字型擴充包 (font extension)**,JRXML 文字樣式要引用該字型,並勾選 Embed to PDF。                                                |

---

### 小結

1. **最簡單**:把 JasperReports Server 當成報表黑盒子 ➜ ASP.NET MVC 以 REST 產生二進位 ➜ `File()` 回傳。
2. **臨時或輕量**:用 JasperReports IO / JasperStarter。
3. **高度互動**:在 Razor 使用 Visualize.js。

遵循上列模式即可讓 .NET 與 JasperReports 平滑整合,無需在 IIS 內部跑 Java,也不必把報表引擎搬到 .NET。

[1]: https://community.jaspersoft.com/documentation/jasperreports-server/tibco-jasperreports-server-rest-api-reference/vv900/jasperreports-server-rest-api-reference-_-reports/?utm_source=chatgpt.com "The reports Service - v9.0.0 - Jaspersoft Community"
[2]: https://community.jaspersoft.com/knowledgebase/getting-started/jasperreports-io-getting-started/?utm_source=chatgpt.com "JasperReports IO - Getting Started - Jaspersoft Community"
[3]: https://www.jaspersoft.com/products/whats-new "What's New | Jaspersoft"

50 Interview Questions - with Answers - on ASP.NET MVC Application Development

# Question Concise Answer
1 What is the core idea behind the MVC pattern? It separates an app into Model (business/data), View (UI), and Controller (request–response logic) so each concern can evolve independently and be unit-tested in isolation.
2 How does the ASP.NET MVC request pipeline differ from Web Forms? MVC uses routing to map URLs to controllers; there is no ViewState or page lifecycle. Each request instantiates a controller, executes an action, returns an IActionResult, then the view engine renders markup.
3 Explain the default route {controller}/{action}/{id?}. It parses a URL like /Orders/Details/5 into controller =Orders, action =Details, optional id =5. If parts are missing it falls back to defaults (e.g., Home/Index).
4 What is attribute routing and when is it useful? Routing rules declared directly on controllers/actions with [Route("api/orders/{id:int}")]. It gives fine-grained, version-friendly URLs—especially for REST APIs.
5 Describe the difference between ViewResult, JsonResult, and FileResult. ViewResult renders a Razor/ASPX view, JsonResult serialises data for AJAX clients, FileResult streams files (bytes) with a MIME type. All derive from ActionResult.
6 How does model binding work? During action invocation MVC inspects form fields, query strings, route values, and JSON; converts them via value providers and binders into action parameters or complex view-models.
7 Why would you create a custom model binder? To map unconventional input (e.g., dd/MM/yyyy dates, combined lat/long strings) or to inject extra context that default binders can’t handle.
8 Explain Data-Annotation-based validation. Attributes such as [Required], [StringLength], [Range] decorate model properties. MVC’s ModelState.IsValid is set during binding; Razor helpers output messages and jQuery Unobtrusive triggers client-side checks.
9 How do TempData, ViewData, and ViewBag differ? ViewData (dictionary) & ViewBag (dynamic) survive only the current request. TempData uses session to persist until read—handy for post-redirect-get patterns.
10 What is bundling and minification? The framework tool that combines (bundles) and compresses (minifies) CSS/JS to cut HTTP requests and payload; configured via BundleConfig.RegisterBundles.
11 Describe Razor syntax advantages. Clean @ delimiters, IntelliSense, compiled to C#, less verbose than ASPX, allows inline C# expressions and conditionals inside HTML.
12 When would you choose a Partial View? For reusable fragments (headers, forms, rows) embedded within other views without a separate controller round-trip.
13 What’s the role of Layout pages? Provide a master template (similar to master pages) so multiple views share consistent HTML shell, scripts, CSS imports.
14 Explain dependency injection (DI) in an MVC app. Controllers depend on abstractions (interfaces). A DI container registered in Startup/Global.asax constructs controllers, injecting services (DB, mail, logging) to enable unit testing and loose coupling.
15 Give an example of registering a service in ASP.NET Core. services.AddScoped<IOrderService, OrderService>(); inside ConfigureServices.
16 Why are asynchronous actions beneficial? With async Task<IActionResult> they free the thread during I/O (DB, HTTP), raising throughput under high concurrency without adding threads.
17 How do you return a 404 in MVC correctly? return HttpNotFound(); (MVC 5) or return NotFound(); (Core) to send status 404 rather than generic server error.
18 What are Action Filters? Attributes that run code before/after action or result execution — used for logging, auth checks, caching, or custom headers.
19 Explain the [ValidateAntiForgeryToken] attribute. It forces MVC to compare a hidden form token with a cookie token, mitigating Cross-Site Request Forgery (CSRF).
20 How can you implement global error handling? MVC 5: add HandleErrorAttribute in FilterConfig plus customErrors in web.config. Core: app.UseExceptionHandler("/Error") middleware or ProblemDetails factory.
21 What is output caching and how do you apply it? Stores rendered view/partial for a duration; in MVC 5 via [OutputCache(Duration=60, VaryByParam="id")]; in Core use ResponseCache or new output-caching middleware (.NET 8).
22 Compare View Components to Partial Views (Core). View components have a C# class, accept parameters, can run async logic, and don’t rely on the current controller—good for widgets (cart, menu).
23 How would you secure an API built with MVC? Use OAuth2/OIDC (e.g., IdentityServer, Azure AD) with JWT Bearer middleware, enforce HTTPS, implement rate limiting, and validate scopes/claims in policies.
24 What is Kestrel? The cross-platform, high-performance web server that hosts ASP.NET Core apps either standalone or behind reverse proxies (IIS, Nginx).
25 Describe the Static Files middleware order. UseStaticFiles() must appear before MVC routing so requests for /css/site.css are short-circuited and don’t hit controllers.
26 How do you stream a large file without buffering? return File(stream, "application/zip", enableRangeProcessing: true); or push chunks with FileStreamResult and Response.BodyWriteAsync.
27 What is the AntiForgeryToken limitation with multiple tabs? Old MVC used per-session token, fine for tabs. Newer double-submit cookie pattern resolves earlier single-tab “request verification failed” issues.
28 Explain the difference between Areas and feature folders. Areas partition big apps into mini-MVC stacks (/Areas/Admin/...). Feature folders (Core) organise by feature (Orders, Users) not by layer, improving cohesion.
29 How do you expose server data to JavaScript safely? Use asp-for tag helpers to emit JSON in data- attributes or serialize via @Html.Raw(Json.Serialize(Model)) with HtmlEncoder.Default to avoid XSS.
30 Why might you choose Razor Pages instead of MVC? Simpler page-centric model, less ceremony, each .cshtml owns its handler methods; still supports DI, filters, model binding. Great for CRUD UIs.
31 What is IActionResult vs ActionResult<T>? Non-generic allows any result type; generic (Core 2.1+) conveys the concrete type in API metadata (Swagger) while still flexible.
32 How do you implement soft deletes in EF Core within MVC? Add IsDeleted flag, override SaveChanges to convert Remove to flag update, filter data with modelBuilder.Entity().HasQueryFilter(e => !e.IsDeleted).
33 Explain HSTS middleware purpose. Adds Strict-Transport-Security header so browsers force HTTPS on subsequent requests, mitigating downgrade attacks.
34 What tooling generates Swagger docs for MVC APIs? Swashbuckle (AddEndpointsApiExplorer, AddSwaggerGen) or NSwag; they read controllers’ attributes and XML comments to produce OpenAPI.
35 How would you profile slow MVC actions? Use Application Insights, MiniProfiler, or diagnostic middleware; wrap actions in Stopwatch, log elapsed time, and analyse traces.
36 Difference between IHostedService and background controller thread hacks. IHostedService (or BackgroundService) is managed by the runtime—graceful shutdown, DI; ad-hoc threads risk orphaning on recycle.
37 What’s new in ASP.NET Core 8 for MVC apps? NativeAOT publish, output-caching middleware, key-value rate limiting, identity UI rebuild on Bootstrap 5, improved Blazor Server-side pre-render.
38 How do you unit-test a Razor view? Traditional MVC views aren’t unit-tested; instead test the controller’s view-model. For Razor Pages/Components you can use Bunit or compile-time checks.
39 Explain the IUrlHelper usage. Generates URLs inside views/controller code respecting routing (Url.Action, Url.Page), keeping links robust when routes change.
40 What are Tag Helpers? Server-side components that run during Razor parsing, e.g., <form asp-action="Login">; they produce standards-compliant HTML with IntelliSense.
41 How do you localise an MVC application? Register IStringLocalizer/IViewLocalizer, create .resx per culture, set RequestLocalizationOptions, and use @Localizer["Greeting"] in views.
42 Describe a Content Security Policy (CSP) header and why add it? Restricts resource sources (script-src, style-src) to mitigate XSS. Add via app.UseCsp() or custom header middleware.
43 What’s the danger of using Thread.Sleep() in an async action? Blocks the thread, defeating async scalability; use await Task.Delay() instead.
44 How do you implement optimistic concurrency in MVC with EF? Add RowVersion byte[]; when SaveChanges detects mismatch it throws DbUpdateConcurrencyException, handle by showing “record changed” message.
45 Explain Difference between IActionFilter and IMiddleware. Action filters wrap MVC actions only; middleware wraps the entire HTTP pipeline — runs earlier, independent of MVC, good for cross-cutting concerns.
46 How would you serve SPA (React/Angular) from MVC? Use UseSpa() in Core with static files; proxy dev server in development; API controllers live side by side.
47 Why keep controllers thin (“fat models/service, thin controllers”)? Maintains Single Responsibility; business logic tested in services not tied to HTTP; controllers orchestrate, improving maintainability.
48 Describe secure file upload steps. Limit size, whitelist MIME and extension, scan for malware, store outside web root, generate random file names, stream to disk not memory.
49 What is Minimal API and can it coexist with MVC? Ultra-light endpoint declarations (MapGet, MapPost) in Program.cs; yes, you can mix Minimal API for simple endpoints and MVC for complex UI.
50 Outline a zero-downtime deployment strategy for MVC on IIS. Use Web Farm / ARR or Azure App Service slots: deploy to staging slot/server, warm-up, then swap; leverage database migrations with Add-Migration & Update-Database guarded by maintenance flag.

These pairs span architecture, security, performance, testing, and modern .NET 8+ features—covering what interviewers typically expect from an experienced ASP.NET MVC developer in 2025.



There isn’t a single “official” count—the exact number of steps depends on the SDLC model you’re following—but the **most commonly taught classical SDLC breaks the work into **7 major phases:


Planning / Feasibility


Requirements Analysis


System & Software Design


Implementation / Coding


Testing & Verification


Deployment / Release


Maintenance & Support


Some organisations merge or split phases (e.g., combining Planning + Requirements into “Inception,” or separating Verification and Validation), so you’ll also see 5-step or 6-step variants. Still, the seven-phase breakdown above is the standard reference in many textbooks and industry guidelines.

Comments

Popular posts from this blog

state government roles website

To enhance embedding in your Retrieval-Augmented Generation (RAG) application

SQL Tutorials 10 hours