跳到主要内容

Routing

1. What is Routing?

Routing decides which endpoint handles an HTTP request, based on:

  • URL path
  • HTTP method

URL + Method → Endpoint


2. Routing Pipeline (Very Important)

Routing happens in two steps:

UseRouting

  • Matches the request to an endpoint
  • Does not execute it

UseEndpoints

  • Executes the matched endpoint
app.UseRouting();

app.UseEndpoints((endpoints) => {
endpoints.MapGet("/hello", async (ctx) => {
await ctx.Response.WriteAsync("Hello");
});
});

UseRouting must come before UseEndpoints.


3. Map* Methods (Create Endpoints)

Common ones:

  • MapGet
  • MapPost
  • MapPut
  • MapDelete
  • MapFallback
endpoints.MapGet("/products", ...);
endpoints.MapPost("/products", ...);

Same path, different HTTP methods → different endpoints.


4. Route Parameters

Required

/products/{id}

Optional

/products/{id?}

Default

/profile/{name=guest}

Access values:

context.Request.RouteValues["id"];

5. Route Constraints

Used to validate route parameters early.

/products/{id:int}
/products/{id:int:range(1,1000)}
/reports/{month:regex(^(jan|apr|jul|oct)$)}

More specific constraints win during matching.


6. Endpoint Selection Rules (Remember This Order)

  1. More specific routes
  2. Exact HTTP method
  3. Stronger constraints
  4. Registration order
  5. Fallback route

7. GetEndpoint()

Used after UseRouting to inspect the matched endpoint.

var endpoint = context.GetEndpoint();

Common for logging, auth, diagnostics.


8. Static Files & Routing

app.UseStaticFiles();
app.UseRouting();
  • Served from wwwroot
  • Bypass routing
  • Faster than endpoints

9. One-Sentence Interview Answer 🎯

"Routing in ASP.NET Core maps incoming HTTP requests to endpoints using URL patterns and HTTP methods. UseRouting matches the request, UseEndpoints executes it, and more specific routes with stricter constraints take priority."