ASP.NET
ASP.NET
Transient,
Scoped,
and Singleton
service lifetimes?- Transient: Created every time. Good for lightweight, stateless services.
- Scoped: Created 1/client request (connection). Any API or web request sharing same HTTP context shares exact same instance.
- Singleton: Only single, identical instance thru app's lifecycle.
- How:
Serializes data into hidden HTML input field (
__VIEWSTATE). - Scope: Single page postbacks.
- Trade-off: Saves server RAM. Hvy network payloads slow page loads. Legacy (Web Forms).
2) Cookies (Client-Side)
How: Text files in browser sent automatically with every HTTP request.
- Scope: Across requests until expiration.
- Trade-off: Great for user preferences. Vulnerable to tampering. Max 4KB size.
3) Query Strings (Client-Side)
How: Appends key-value pairs to URL end (
?id=123).Scope: Single targeted HTTP request.
Trade-off: Easy setup. Shareable/bookmarkable. Insecure; data visible in address bar.
4) Session State (Server-Side)
How: Stores data on server. Links client via unique Session ID cookie.
Scope: Single user across active browser session.
Trade-off: Secures data. Consumes server RAM unless offloaded to Redis/SQL.
5) App State (Server-Side)
How: Global variables put in server memory (
HttpAppState).Scope: All users, all requests.
Trade-off: Perfect for global config. Requires locks (
Lock/Unlock) to avoid thread collision.
Q3: MVC Lifecycle (7 Core Events)
1.
Routing - UrlRoutingModule
gets HTTP request, parses URL, matches route table patterns, extracts
controller/action names.
2.
Route Handler - Extracts
MvcRouteHandler.
Creates request context. Instantiates MvcHandler
to run pipeline.
3.
Controller Factory - MvcHandler
calls DefaultControllerFactory.
Uses reflection to find, load, instantiate target controller.
4.
Actions - ActionInvoker
triggers. Binds model inputs. Runs authorization filters. Runs C#
controller method.
5.
Results - Controller
method returns ViewResult,
JsonResult.
6.
View Engine - Locates
.cshtml
file (usually via Razor). Compiles layout. Injects controller data
into raw HTML.
7. Response - Pushes final HTML/JSON stream to HTTP response pipeline. Sends packet to browser. Ends lifecycle.
Q4:
Diff ViewData,
ViewBag,
and TempData
in MVC.
ViewData:
ViewDataDictionarychild stores in Key/Value objects so must cast.ViewBag:
ViewDatawrapper rids type casting but no compile-time type safety.TempData:
TempDataDictionarychild that persists data until it is read.
Q4: Role of Kestrel web server and why paired with IIS or Nginx?
Kestrel: Fast, cross-platform HTTP server built natively into ASP.NET Core to process raw Asynch requests.
Edge Security: Kestrel lacks auto SSL mgmt, request throttling, and complex load balancing.
Reverse Proxy Pairing: IIS or Nginx route clean requests to Kestrel.
Q5:
Diff IEnumerable
and IQueryable
in EF Core.
IEnumerable: Queries DB and pulls all data into server memory. Later filters done in-memory.
IQueryable: Lazy running of queries. Applies filters (
Where,Take) at DB before running SQL.
Q6: Fix SQL Injection and Cross-Site Request Forgery attacks?
SQL Injection: Use EF Core params or
FromSqlRawto stop malicious string concat.CSRF Mitigation: Use
[ValidateAntiForgeryToken]or global auto-validation middleware. Razor forms should have hidden anti-forgery token via standard tag helpers.
Q7: "N+1 Query Problem" in EF Core and how fix?
Problem: App queries Invoice and then Invoice Line Item in a loop.
Cause: Over rely on Lazy Loading causes lots of unexpected SQL trips per Invoice Line Item.
Solution: Eager Load via the
.Include()and.ThenInclude()to join tables and fetch all data in one SQL.
Q8:
How Asynch (async/await)
scales?
Thread Conservation: Stops thread starvation by releasing active thread back to thread pool while waiting for I/O or DB calls.
Throughput Boost: While external I/O task runs, thread handles other web requests.
Important: Asynch not faster; but increases the total volume of simultaneous requests the server can manage.
Q9: Tag Helpers and how differ from HTML Helpers?
Tag Helpers: Server-side C# code in creating and rendering HTML elements in Razor files. Looks like standard HTML tags (e.g.,
<a asp-controller="Home">).HTML Helpers: Rendered as raw C# method invocations mixed into the HTML markup (e.g.,
@Html.ActionLink("Home", "Index")).Advantages: Clean syntax, integrates with front-end tooling, and IntelliSense.
Q10: Content Negotiation in ASP.NET Core Web API, and how work?
Definition: Server picks the best format (JSON or XML) to return.
Mechanism: Server inspects the incoming
Acceptheader sent by the client's HTTP request.Default: ASP.NET Core defaults to JSON output. Configure the XML serializer in
Program.csusing.AddXmlSerializerFormatters()to support XML requests.
Q11: Model Binding and Validation.
Model Binding: Auto maps HTTP request data (query strings, route data, form fields, or request bodies) into controller action params.
Validation: Uses
[Required]or[StringLength]applied directly to DTO properties.Evaluation: Tracks validation status in
ModelState.IsValid. In Web APIs decorated with[ApiController], failed validation triggers 400 Bad Request response.
Q12: How handle Dev, Staging, Prod configs?
Environ Variable:
ASPNETCORE_ENVIRONMENT.JSON Files: Configs load hierarchically from matching files like
appsettings.jsonandappsettings.Development.json.Overriding Rule: Environ-specific JSON file overwrites dup keys found in base config.
Q13:
"Options Pattern" and IOptions,
IOptionsSnapshot,
and IOptionsMonitor?
Options Pattern: Groups, validates, and injects related config settings via DI.
IOptions: Singleton. Reads configs once in startup and never updates until the app restarts.
IOptionsSnapshot: Scoped lifecycle. Reevaluates configs on every new HTTP request.
IOptionsMonitor: Singleton. Deliver real-time config changes via an
OnChangeevent notifier.
Q14: Structured Logging and why better than flat text logs?
Structured Logging: Creates key-value pairs inside JSON or other instead of a flat string.
Flat Text Drawback: Parsing flat text files requires complex reg ex.
Search Advantage: Log analysis systems (like Serilog paired with ELK or Seq) can instantly index and filter specific properties (e.g.,
CustomerId == 5) across millions of entries.
Q15: Rate Limiting and how do it.
Built-in Middleware: Native rate-limiting middleware configured in
Program.cs.Core Algorithms: Fixed Window, Sliding Window, Token Bucket, and Concurrency limits.
app Rule: Set rate-limiting policies globally or target specific routes using
[EnableRateLimiting]attribute to defend against DoS attacks.
Q16: Filter Pipelines and execution order of 5 filters?
Filter Pipelines: Custom code run before or after specific stages in invocation pipeline.
1. Authorization Filters: Sees if user is fully verified and authorized for resource.
2. Resource Filters: Looks at request and returns cached response.
3. Action Filters: Runs right before and immediately after controller action method runs.
4. Exception Filters: Handles unhandled controller actions or model binders exceptions.
5. Result Filters: Before and after final action result renders.
Comments
Post a Comment