0

I'm looking for a way to have multiple routes in my ASP.NET Core which differ by a certain header. I found this question which answers the same question BUT for a controllers-based API: Header based routing in ASP.NET Core

I'm looking for the same thing, but for a Minimal APIs. I found this (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-8.0#route-constraints) describing custom route constraints, but I don't really care about any parameters (my path actually doesn't have any) so I don't know how to use it.

3
  • 1
    How many routes are we talking here? If it's just a handful then you're better-off having a single "normal" Action/Handler or Middleware func that inspects the request header and simply makes a direct method-call - it really isn't worth the effort to get into the ductwork of ASP.NET's infra unless the effort-to-reward ratio is there (though if you're wanting to do it for learning reasons or for a challenge, that's different - I assume you're just wanting to do things properly but your boss/client would rather you shipped something sooner, even if internally it's not pretty to look at. Commented Aug 11, 2024 at 12:26
  • 1
    (I wryly note that "Minimal API" in ASP.NET Core started-off as an attempt to lower-the-barier-of-entry for ASP.NET to avoid overwhelming newcomers with the Startup ceremony - but now it's a meaningless buzzword because using "Minimal API" does nothing to help prevent projects of nontrivial complexity ending up as a hot mess after spending 5-6 years in prod, or worse: handing it off to a 1st-year intern) Commented Aug 11, 2024 at 12:29
  • You're right it's just a few routes and I already spent more time with it than is justifiable 😅 but Im taking it as a learning opportunity Commented Aug 13, 2024 at 7:48

1 Answer 1

1

Following code works to map minimal endpoints conditionally.

app.UseRouting();
app.MapWhen(context => context.Request.Headers["route"]=="A", (appBuilder) =>
{
    appBuilder.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("A", () => { return "A result"; });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.