ASP.NET Core MVC Request Lifecycle – From Browser to View

๐Ÿ” ASP.NET Core MVC Request Lifecycle – From Browser to View

๐Ÿ” What Happens When a Request Comes from the Browser in ASP.NET Core MVC?

Understand the journey of a request in ASP.NET Core MVC — from browser to controller, through services, and back as a rendered Razor view.

๐ŸŒ 1. The Journey Begins: Browser Sends a Request

Every user action — like clicking a link or submitting a form — sends an HTTP request to your ASP.NET Core MVC application. The request first hits the Kestrel Web Server and flows through the middleware pipeline.

This pipeline is configured in Program.cs and typically looks like this:


var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IProductService, ProductService>(); // Dependency Injection

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseStatusCodePagesWithReExecute("/Home/StatusCode", "?code={0}");
}
else
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication(); // Important order
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

๐Ÿงฑ Visual Flowchart

+---------------------+
|     Browser         |
+---------------------+
          |
          v
+---------------------+
|     Kestrel Server  |
+---------------------+
          |
          v
+-------------------------------+
|  Middleware Pipeline          |
| - HTTPS Redirection           |
| - Static Files                |
| - Routing                     |
| - Authentication              |
| - Authorization               |
+-------------------------------+
          |
          v
+---------------------+
|    Controller       |
+---------------------+
          |
          v
+---------------------+
|      Services       |
+---------------------+
          |
          v
+---------------------+
| Razor View Engine   |
+---------------------+
          |
          v
+---------------------+
|   HTML Response     |
+---------------------+

๐Ÿ›ฃ️ 2. Routing Middleware and Controller

The routing system maps the URL to a controller action:

https://example.com/Product/Details/5

This route resolves to:

  • Controller: ProductController
  • Action: Details
  • Parameter: id = 5

[Authorize] // Authorization filter
public class ProductController : Controller
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }

    public IActionResult Details(int id)
    {
        var product = _productService.GetProductById(id);
        if (product == null)
        {
            return NotFound(); // 404
        }
        return View(product);
    }
}

๐Ÿงฉ Filter Execution Order (Simplified)

  • Authorization filters (e.g., [Authorize]) run first.
  • Action filters (e.g., OnActionExecuting()) run before/after the controller action.
  • Result filters run before/after the result (view) is processed.
  • Exception filters handle unhandled exceptions.

public class LogActionFilter : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        Console.WriteLine("Before Action");
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        Console.WriteLine("After Action");
    }
}

๐Ÿง  3. Model and Business Logic

The service layer handles business logic and often uses repositories to query the database.


public interface IProductService
{
    Product GetProductById(int id);
}

public class ProductService : IProductService
{
    public Product GetProductById(int id)
    {
        // DB logic or caching
        return new Product { Id = id, ProductName = "Shoes", Price = 2999 };
    }
}

๐Ÿ–ผ️ 4. View: Razor Rendering

Views are written using Razor syntax and return the final HTML to the browser.


@model Product
<h2>@Model.ProductName</h2>
<p>Price: ₹@Model.Price</p>

๐Ÿงฉ Razor View Engine Extras

  • _Layout.cshtml: Shared page layout with headers/footers
  • _ViewStart.cshtml: Automatically applies layout to all views
  • Partial Views: Reusable view components like _ProductCard.cshtml

These files enable modular UI development in large apps.

๐Ÿงช Real-world Analogy

Imagine you're in a restaurant:

  • ๐Ÿฝ️ You (browser) place an order.
  • ๐Ÿ‘จ‍๐Ÿณ The manager (controller) interprets it and sends it to the kitchen (service/model).
  • ๐Ÿง‘‍๐Ÿฝ️ The waiter (view) brings your meal (HTML) to the table.

๐Ÿ“Œ Summary of Request Lifecycle

Browser
  ↓
Kestrel Server
  ↓
Middleware (HTTPS, StaticFiles, Auth, Routing)
  ↓
Filters (Authorize, Action, Exception)
  ↓
Controller
  ↓
Service / Model
  ↓
View Rendering
  ↓
HTML Response

๐Ÿง  Key Takeaways

  • ✔️ Middleware order defines how the request is processed.
  • ✔️ Controllers delegate to services using DI.
  • ✔️ Filters help enforce security, logging, or validation.
  • ✔️ Razor View Engine renders the final HTML using layout and partial views.

๐Ÿ“ฃ Like this guide? Share it or comment below. Follow for more in-depth ASP.NET Core tutorials!

Comments

Popular posts from this blog

Multiline to singleline IN C# - CODING

EF Core interview questions for beginners

EF Core interview questions for experienced