Guozhen AIGlobal AI field notes and model intelligence

English translation

ASP.NET Core Routing and Built-in Middleware Usage

Published:

Category: ASP.NET

Read time: 3 min

Reads: 0

Lesson #12Views are counted together with the original Chinese articleImages are preserved from the source page

AI Article Decision Snapshot

Turn the lesson into workflow, model, budget, and security checks before choosing tools.

Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.

Workflow fit

Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.

Model or tool decision

Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.

Budget and usage signal

Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.

Security and privacy review

Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.

In the ASP.NET Core framework, middleware forms a core component of application construction, responsible for handling various stages of HTTP requests and responses. In the previous section, we explored how to configure middleware; today, we’ll delve deeper into using the built-in middleware provided by ASP.NET Core. These middleware components enable developers to rapidly implement common functionalities—such as authentication, session management, and static file serving—without writing everything from scratch.

1. Static Files Middleware

ASP.NET Core includes a highly practical built-in middleware that serves static files—such as HTML, CSS, JavaScript, and images—directly from your application server. Using this middleware simplifies delivering static assets to clients.

Example Code

First, configure the static files middleware in Startup.cs:

public class Startup
{
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Enable static files middleware
        app.UseStaticFiles();

        // Other middleware configurations
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", async context =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        });
    }
}

Here, app.UseStaticFiles() enables the application to serve static files directly from the wwwroot folder. If your project structure resembles the following:

/MyAspNetCoreApp
|-- /wwwroot
|   |-- css
|   |   |-- style.css
|   |-- js
|   |   |-- app.js
|   |-- index.html
|-- Startup.cs

You can access static files via your browser—for example, navigate to http://localhost:5000/index.html.

2. Logging Middleware

ASP.NET Core provides robust logging capabilities. Built-in middleware allows you to easily log request and response details—e.g., recording request information when it enters the pipeline and response information when it exits.

Example Code

In Startup.cs, you can add simple logging middleware like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
    app.Use(async (context, next) =>
    {
        logger.LogInformation("Handling request: " + context.Request.Path);
        await next.Invoke();
        logger.LogInformation("Finished handling request.");
    });

    app.UseRouting();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            await context.Response.WriteAsync("Hello World with Logging!");
        });
    });
}

In this example, a custom inline middleware logs the request path before and after processing. Information is recorded both when the request enters and when the response is sent back.

3. Authentication Middleware

ASP.NET Core supports multiple authentication schemes—including Cookie-based and JWT-based authentication. Authentication middleware helps protect your application by ensuring users are authenticated before accessing restricted resources.

Example Code

Below is an example configuring simple Cookie-based authentication middleware:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication("MyCookieAuth")
        .AddCookie("MyCookieAuth", options =>
        {
            options.LoginPath = "/Account/Login";
        });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication(); // Add authentication middleware

    app.UseRouting();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            await context.Response.WriteAsync("Hello World with Authentication!");
        });
    });
}

In this example, Cookie authentication is configured in ConfigureServices(). Then, app.UseAuthentication() registers the authentication middleware in the request pipeline within Configure().

4. Error-Handling Middleware

Handling errors gracefully is a common requirement. ASP.NET Core provides the UseExceptionHandler middleware to catch and manage unhandled exceptions.

Example Code

Here’s how to set up basic error handling:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseExceptionHandler("/Home/Error"); // Configure exception handler

    app.UseRouting();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            throw new Exception("Test Exception");
        });

        endpoints.MapGet("/Home/Error", async context =>
        {
            await context.Response.WriteAsync("An error occurred!");
        });
    });
}

In this example, if an unhandled exception occurs on the root path (/), the user is redirected to /Home/Error, where the error message is displayed.

Summary

By understanding and leveraging ASP.NET Core’s built-in middleware, developers can efficiently implement many common features without building them from scratch. In this section, we covered four essential middleware types:

  • Static Files Middleware — for serving frontend assets,
  • Logging Middleware — for tracing request/response flow,
  • Authentication Middleware — for securing protected resources, and
  • Error-Handling Middleware — for graceful exception recovery.

These tools help you build more robust, maintainable, and production-ready applications.

Next, we’ll move on to the Controllers and Views chapter, where we’ll explore controller creation and usage in depth.

Apply This Lesson

Turn this article into AI software, model, API, and security decisions.

English Article FAQ

Use this article as evidence before choosing AI tools

How should I use this AI Tutorials article?

Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.

Is this English article different from the Chinese original?

The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.

What should I read after ASP.NET Core Routing and Built-in Middleware Usage?

Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.

Can this article alone choose an AI product or model?

No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.

Continue

Keep reading from here

Browse English site

Reader Messages

Reader messages

Questions, corrections, extra sources, or hands-on results can be left here. No login is required.

Max 800 characters

To reduce spam, each message is checked for length, link count, and posting frequency.

0/800

Messages

0 messages
Loading messages...