أسئلة القسم
تدرب على أسئلة المقابلات في هذا القسم. اكتب إجابتك، قم بتقييمها، أو اضغط على "عرض الإجابة" بعد التفكير.
What’s the difference between ASP.NET MVC and ASP.NET Web Forms? When should you use each? سهل
Aspect | ASP.NET MVC | ASP.NET Web Forms |
---|---|---|
Pattern | Model–View–Controller | Event-driven, Page–Controller |
Separation of Concerns | Strong separation | Tight coupling of UI & logic |
HTML/JS Control | Full control over markup | Uses server controls, ViewState |
Testability | High | Low |
Performance | Lightweight, no ViewState | Heavier due to ViewState |
Learning Curve | Steeper | Easier for WinForms devs |
When to use:
MVC: For modern, testable, SEO-friendly apps requiring fine-grained HTML control. Web Forms: For rapid internal apps where drag-and-drop UI and server controls are desired.
Explain MVC Life cycle سهل
- Routing – URL matched to route.
- Controller Initialization – Controller instance created.
- Action Execution – Action method runs.
- Result Execution – Action returns a result (often a ViewResult).
- View Rendering – Razor engine renders the View to HTML.
What is Rest API? سهل
REST (Representational State Transfer) is an architectural style for building APIs. Uses HTTP verbs to perform CRUD operations on resources (nouns). Stateless: each request contains all info needed. Returns representations like JSON or XML.
Explain the difference between GET, POST, and PATCH in HTTP APIs. سهل
HTTP Verb | Purpose | Idempotent? | Example |
---|---|---|---|
GET | Retrieve data | ✅ Yes | /api/products/1 |
POST | Create new resource | ❌ No | /api/products with body |
PATCH | Partial update of a resource | ❌ No | /api/products/1 with partial JSON |
Difference between MVC and Razor Pages in .NET Core? سهل
Feature | MVC | Razor Pages |
---|---|---|
Structure | Separate Controller + View | Page-centric, code-behind model |
Complexity | Good for large apps | Simpler for small/medium apps |
Routing | Convention + Attributes | Built-in page-based routing |
Testability | High | Also testable but less boilerplate |
What is Scaffolding in MVC? سهل
Automated code generation feature. Quickly creates Controllers, Views, and CRUD actions from a Model. Saves time in prototyping.
What is a Partial View? سهل
A reusable Razor View chunk (like a UserControl). Does not run as a full view; rendered inside another view. Used for headers, footers, sidebars, or shared UI parts.
How do you transfer data from a Controller → View? سهل
- ViewBag (dynamic, short-lived)
- ViewData (dictionary, short-lived)
- TempData (persists across redirect)
- Strongly-Typed Model (best practice)
Example:
public IActionResult Index() {
var model = new ProductViewModel();
return View(model); // strongly-typed
}
What is a DTO (Data Transfer Object)? سهل
A simple object used to transfer data between layers or over the network. No business logic, just properties. Protects your domain models from exposure and reduces payload.
What is the purpose of [NonAction] attribute? سهل
Applied to public methods in a Controller to prevent them from being treated as Actions. Ensures method can be called internally but not via HTTP request.
What is early binding and late binding? سهل
Binding | Meaning | Example |
---|---|---|
Early Binding | Method/member known at compile-time. Faster & type-safe. | Normal C# method call. |
Late Binding | Resolved at runtime. Slower, less type-safe. | Reflection, dynamic keyword. |
What is token? متوسط
A piece of data (usually a string) used to authenticate or authorize a user. Examples: Session tokens, OAuth access tokens, JWTs. Carries claims/permissions instead of using cookies.
What is JWT? متوسط
Open standard (RFC 7519) for secure transmission of claims. Consists of Header, Payload, Signature. Self-contained: server doesn’t store session state.
What is different between Authorization and Authentication? متوسط
Term | Meaning |
---|---|
Authentication | Verifying identity (login) |
Authorization | Verifying permissions (what they can access) |
How does Routing work in ASP.NET Core, and what are Attribute Routes? متوسط
Routing: Matches incoming URL to endpoint (controller/action or Razor page). By default, uses convention-based routing defined in Program.cs. Attribute Routing: Decorating controllers/actions with [Route] to define URL patterns explicitly.
What is Middleware in ASP.NET Core, and how do you create a custom middleware? متوسط
Components that handle requests/responses in a pipeline. Registered in Program.cs using app.Use....
Creating custom middleware:
public class MyMiddleware {
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext context) {
await _next(context);
}
}
// In Program.cs
app.UseMiddleware<MyMiddleware>();
How does Middleware pipeline work in .NET Core? متوسط
Request enters → passes each middleware in order → endpoint executes → response travels back through middlewares. Order matters.
What are Action Filters and when to use them? متوسط
Special attributes that run before or after controller actions. Used for cross-cutting concerns: logging, validation, caching.
What is the difference between Middleware and ActionFilters? متوسط
Feature | Middleware | Action Filter |
---|---|---|
Scope | Whole pipeline (all requests) | Specific controller/actions |
When it runs | Before MVC executes | Around action execution inside MVC |
Use Cases | Auth, logging, compression | Validation, custom logic per action |
What is an Anti-Forgery Token and why is it used? متوسط
Prevents Cross-Site Request Forgery (CSRF) attacks.
Ensures request is from the authenticated user’s browser.
ASP.NET Core: @Html.AntiForgeryToken()
in view + [ValidateAntiForgeryToken]
in action.
Is there any limit to the GET request’s length? If yes, where is such a limit configured? What about POST? متوسط
HTTP spec doesn’t set a hard limit. The web server or browser imposes limits:
- IIS default max URL length ≈ 16 KB.
- ASP.NET Core’s Kestrel has higher defaults but still limited by OS. POST body size can be configured (e.g. MaxRequestBodySize).
What are Kestrel and IIS, and how do they work with .NET Core applications? متوسط
Kestrel: Cross-platform, lightweight, built-in web server for ASP.NET Core. Always used. IIS: Windows-only, full-featured web server.
How they work:
ASP.NET Core runs on Kestrel internally. On Windows, you often put IIS in front as a reverse proxy (handles SSL termination, process management). On Linux you’d use Nginx/Apache in front.
Difference between ControllerBase and Controller in Web API. متوسط
Class | Contains | Typical Use |
---|---|---|
ControllerBase | API-only features (routing, model binding, HTTP helpers) | Web API controllers (no views) |
Controller | Inherits ControllerBase + View support (View(), PartialView()) | MVC controllers returning views |
What is alias in API? متوسط
Alternate route name for the same endpoint using multiple [Route] attributes.
What are the dependency injection scopes in ASP.NET? متوسط
- Transient: New instance every time requested.
- Scoped: One instance per request.
- Singleton: One instance for the lifetime of the app.
What is the types of lifetimes we use with Dependency injection and difference between them? متوسط
Lifetime | Created | Typical Use |
---|---|---|
Transient | Every injection | Lightweight, stateless services |
Scoped | Once per request | DB contexts, unit of work |
Singleton | App lifetime | Config, caching |
How can dependency injection be helpful in testing? متوسط
Allows you to swap real implementations with mocks/fakes. Your code depends on interfaces, not concrete classes.
What is IHttpClientFactory used for, and which issues does it help to eliminate? متوسط
Central factory to create HttpClient instances. Solves socket exhaustion & DNS issues. Centralized config & resilience (policies, retries with Polly).
What is wrong with creating HttpClient manually? متوسط
If you new HttpClient() repeatedly:
- OS sockets not released fast enough (socket exhaustion).
- DNS changes not respected. Recommended: one long-lived instance or use IHttpClientFactory.
What is asynchronous programming in .NET, and why is it important? متوسط
Uses async/await to free threads during I/O operations. Increases scalability and responsiveness (especially for web apps). Doesn’t block the request thread.
What’s the difference between await AsyncMethod() and AsyncMethod().Result? متوسط
Expression | Behavior |
---|---|
await AsyncMethod() |
Asynchronously waits without blocking current thread. |
AsyncMethod().Result |
Blocks until result available; can cause deadlocks. |
How would you handle exceptions in MVC? صعب
Use Exception Filters (IExceptionFilter) for controller-level errors. Use middleware for global exception handling. Configure custom error pages in Program.cs with app.UseExceptionHandler().
How would you secure your WebAPI? صعب
- HTTPS only.
- Authentication (JWT, OAuth, API Keys).
- Authorization (roles, policies).
- Input validation + Anti-forgery where needed.
- Rate limiting / throttling.
What is the flow of generating, obtaining, and passing JWT token in a .NET application? صعب
- User sends credentials to Auth endpoint.
- Server validates and issues JWT (signed).
- Client stores JWT (localStorage, cookies).
- Client sends JWT in Authorization: Bearer
header for each request. - Server middleware validates token signature and claims.
When using JWT tokens in an API, how does the server ensure it talks to a legitimate client? صعب
- Server verifies signature with secret/public key.
- Checks issuer, audience, expiration claims.
- (Optional) Use TLS and extra device checks.
Is the API security compromised when the user’s JWT token is stolen? صعب
Yes. JWT is bearer token: anyone holding it can act as user until it expires. Mitigations: Short lifetimes + refresh tokens, revoke via blacklists.
Explain Caching strategies in ASP.NET Core. صعب
- In-Memory Cache: per app instance.
- Distributed Cache: Redis/SQL for multi-server scenarios.
- Response Caching: caches entire HTTP responses.
- Output caching (new in .NET 8): caches action results.
Write the complete steps/code for creating an HTTP POST API - taking a request and returning response in JSON. صعب
[HttpPost("products")]
public IActionResult Create([FromBody] ProductDto dto) {
// validate & save
return CreatedAtAction(nameof(GetById), new { id = 1 }, dto);
}
Write a Custom Middleware (with Invoke method). صعب
public class MyMiddleware {
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext context) {
// pre logic
await _next(context);
// post logic
}
}
// registration:
app.UseMiddleware<MyMiddleware>();
What is gRPC and how is it different from REST APIs? صعب
Feature | gRPC | REST |
---|---|---|
Protocol | HTTP/2 | HTTP 1.1/2 |
Data Format | Protobuf (binary) | JSON/XML |
Speed | Faster, smaller payloads | Slower |
Streaming | Built-in bidirectional streaming | Limited |
Write different ways for API Versioning in .NET Core. صعب
- URL versioning: /api/v1/products
- Query string: ?api-version=1.0
- Header versioning: X-Version:1
- Use Microsoft’s Asp.Versioning NuGet for built-in support.
Write code/steps to Upload & Retrieve an image from Azure Blob Storage. صعب
Upload:
var blob = container.GetBlobClient("image.jpg");
await blob.UploadAsync(stream);
Retrieve:
var blob = container.GetBlobClient("image.jpg");
var download = await blob.DownloadAsync();
Write steps to create an API in .NET. صعب
- dotnet new webapi
- Add Models
- Add DbContext (if needed)
- Add Controllers
- Configure DI and routing
- Test with Swagger.
Write code to call an API from a .NET client. صعب
var client = httpClientFactory.CreateClient();
var response = await client.GetAsync("https://api.example.com/data");
var content = await response.Content.ReadAsStringAsync();