Skip to main content

How ASP.NET Core Handles Requests

Level: Beginner

ℹ️ Where This Fits

The request pipeline explains what happens after a browser, mobile app, or frontend sends a request. This is the foundation for middleware, routing, controllers, authentication, CORS, and error handling.

ℹ️ What You'll Learn
  • HTTP request structure: Method, URL, Headers, Body (Student POST request example)
  • HTTP response structure: Status code, Headers, Body (200 OK with JSON data)
  • Request pipeline flow: Request → Middleware 1 → Middleware 2 → Routing → Handler → Response
  • Middleware order matters: Exception handling (first) → Logging → Authentication → Routing (last)
  • How routing matches URLs: /students/{id} finds correct handler with parameters
  • Response traveling back through middleware in reverse order
  • Common HTTP status codes: 200 (OK), 201 (Created), 400 (Bad Request), 401 (Unauthorized), 404 (Not Found), 500 (Error)
  • Real School Management example: Teacher marks attendance → POST /attendance/mark → Handler processes → 200 OK response
  • HTTP methods and meaning: GET (read), POST (create), PUT (update), PATCH (partial), DELETE (remove)
  • Middleware can stop request: Authentication middleware blocks unauthorized users before routing
  • Request context: HttpContext contains Request, Response, User, Items
  • Debugging pipeline: Using logging middleware to trace request flow

Every web application does this:

Receive request -> Process request -> Send response

ASP.NET Core organizes that flow using the request pipeline.

What is a Request?

A request is a message sent from a client to the server.

The client can be:

  • Browser
  • React/Angular app
  • Mobile app
  • Postman
  • Another backend system

School example:

POST /attendance/mark
Content-Type: application/json

{
"studentId": 101,
"date": "2026-05-27",
"isPresent": true
}

This request says:

Please mark attendance for student 101.

What is a Response?

A response is the server's answer.

Example:

HTTP/1.1 200 OK
Content-Type: application/json

{
"success": true,
"message": "Attendance marked"
}

The response tells the client whether the request succeeded or failed.

Request Pipeline in Simple Words

The request pipeline is the ordered list of steps a request passes through.

Request
v
Middleware 1
v
Middleware 2
v
Routing
v
Endpoint / Controller
v
Response

Response comes back in reverse order:

Endpoint creates response
v
Middleware 2 can inspect response
v
Middleware 1 can inspect response
v
Client receives response

Why Middleware Exists

Many tasks are needed for every request:

  • Logging
  • Error handling
  • HTTPS redirection
  • Static file handling
  • CORS
  • Authentication
  • Authorization

Instead of writing these again in every route, ASP.NET Core uses middleware.

Real School Request Flow

Teacher clicks Mark Attendance.

1. Browser sends POST /attendance/mark
2. Logging middleware logs request
3. Error handling middleware prepares to catch errors
4. Authentication checks teacher is logged in
5. Authorization checks teacher has permission
6. Routing finds attendance endpoint
7. Endpoint validates data
8. Attendance service saves to database
9. Endpoint returns 200 OK
10. Logging middleware logs response
11. Browser shows success message

Code Example

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Use(async (context, next) =>
{
Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}");

await next();

Console.WriteLine($"Response: {context.Response.StatusCode}");
});

app.MapGet("/students/{id}", (int id) =>
{
return Results.Ok(new
{
Id = id,
Name = $"Student {id}"
});
});

app.Run();

What happens for /students/101:

Request log printed
Route handler runs
JSON response is created
Response log printed
Client receives JSON

Middleware Can Stop a Request

Middleware does not always call the next step.

Example:

app.Use(async (context, next) =>
{
bool isBlocked = context.Request.Path.StartsWithSegments("/blocked");

if (isBlocked)
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Access denied");
return;
}

await next();
});

If the URL starts with /blocked, the request stops there.

HTTP Methods

MethodMeaningSchool Example
GETRead dataGet student details
POSTCreate dataAdd a new student
PUTReplace/update dataUpdate full student profile
PATCHPartial updateUpdate only phone number
DELETEDelete dataRemove old draft record

HTTP Status Codes

CodeMeaningExample
200OKStudent found
201CreatedNew student added
400Bad RequestMissing student name
401UnauthorizedUser not logged in
403ForbiddenStudent trying to access admin report
404Not FoundStudent id does not exist
500Server ErrorUnexpected exception

Good Pipeline Order

Typical order:

app.UseExceptionHandler("/error");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Why order matters:

  • Error handling should be early so it can catch later errors.
  • Static files should run before expensive app logic.
  • Authentication must run before authorization.
  • Endpoints/controllers are mapped after middleware.

Common Beginner Mistakes

MistakeProblem
Thinking middleware and route handlers are the sameMiddleware surrounds many requests; handlers process specific endpoints
Wrong auth orderAuthorization cannot work correctly before authentication
Forgetting await next()Request may stop too early
Calling next() twiceCan cause unexpected behavior
Not returning after blocking requestLater middleware may still run

Summary

ConceptMeaning
RequestClient asks server for something
ResponseServer answers
PipelineOrdered request processing flow
MiddlewareReusable processing step
RoutingFinds matching endpoint
EndpointYour C# code that handles request
ℹ️ Key Idea

Most ASP.NET Core features are easier after you understand the pipeline. Middleware, routing, controllers, CORS, authentication, authorization, and error handling all depend on this mental model.

🎯 Interview Favourite

Q: Explain the ASP.NET Core request pipeline.

Good Answer: "The request pipeline is the ordered flow an HTTP request follows inside an ASP.NET Core application. A request enters middleware one by one. Middleware can inspect, modify, stop, or pass the request to the next component. After middleware, routing selects the matching endpoint or controller action. The endpoint creates a response, and the response travels back through middleware before going to the client. Middleware order matters, especially for error handling, routing, authentication, and authorization."

Practice Before Next Article

  1. Explain request and response with a school attendance example.
  2. Write the correct order: authentication or authorization first?
  3. What happens if middleware does not call next()?
  4. List five common HTTP status codes.
  5. Explain why error handling middleware should be early.
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on ASP.NET Core request pipeline. Try these prompts:

  • "Explain the request pipeline like I am a beginner"
  • "Give me a real example of middleware stopping a request"
  • "Why does middleware order matter?"
  • "Create a diagram for request and response flow"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

-> Middleware - Building Custom Request Processors

nexcoding.in